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 |
|---|---|---|---|---|---|
nit: we've followed the pattern where the sync APIs call their next max overloads -> this sync API should call the sync API overload with Context.NONE. | public PagedIterable<String> query(String query) {
return new PagedIterable<>(digitalTwinsAsyncClient.query(query));
} | return new PagedIterable<>(digitalTwinsAsyncClient.query(query)); | public PagedIterable<String> query(String query) {
return query(query, Context.NONE);
} | class to deserialize the application/json component into.
* @param <T> The generic type to deserialize the component to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link DigitalTwinsResponse} | class to deserialize the application/json component into.
* @param <T> The generic type to deserialize the component to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link DigitalTwinsResponse} |
It does not need it but no harm in passing it as well. To keep it consistent with .net, I will remove it here. | public PagedFlux<String> query(String query) {
return new PagedFlux<>(
() -> withContext(context -> queryFirstPage(query, context)),
nextLink -> withContext(context -> queryNextPage(query, nextLink, context)));
} | nextLink -> withContext(context -> queryNextPage(query, nextLink, context))); | public PagedFlux<String> query(String query) {
return new PagedFlux<>(
() -> withContext(context -> queryFirstPage(query, context)),
nextLink -> withContext(context -> queryNextPage(nextLink, context)));
} | class to deserialize the application/json component into.
* @param <T> The generic type to deserialize the component to.
* @return A {@link DigitalTwinsResponse} | class to deserialize the application/json component into.
* @param <T> The generic type to deserialize the component to.
* @return A {@link DigitalTwinsResponse} |
From the .NET client, it looks like all we need to supply to the service is the cont. token, we don't need to pass in the query string again: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/digitaltwins/Azure.DigitalTwins.Core/src/DigitalTwinsClient.cs#L1360-L1363 Also, what is our testing strategy with this (the pageable part)? Do we create 100+ twin instances and then query them? The page size isn't configurable yet, correct? | Mono<PagedResponse<String>> queryNextPage(String query, String nextLink, Context context) {
QuerySpecification querySpecification = new QuerySpecification();
querySpecification
.setQuery(query)
.setContinuationToken(nextLink);
return protocolLayer
.getQueries()
.queryTwinsWithResponseAsync(querySpecification, context)
.map(objectPagedResponse -> new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
objectPagedResponse.getValue().getItems().stream()
.map(object -> {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.error("JsonProcessingException occurred while retrieving query result items: ", e);
throw new RuntimeException("JsonProcessingException occurred while retrieving query result items", e);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList()),
objectPagedResponse.getValue().getContinuationToken(),
objectPagedResponse.getDeserializedHeaders()));
} | .setQuery(query) | new QuerySpecification().setQuery(query);
return protocolLayer
.getQueries()
.queryTwinsWithResponseAsync(querySpecification, context)
.map(objectPagedResponse -> new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
objectPagedResponse.getValue().getItems().stream()
.map(object -> {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.error("JsonProcessingException occurred while retrieving query result items: ", e);
throw new RuntimeException("JsonProcessingException occurred while retrieving query result items", e);
}
} | class to convert the query response to.
* @param <T> The generic type to convert the query response to.
* @return A {@link PagedFlux} | class to convert the query response to.
* @param <T> The generic type to convert the query response to.
* @return A {@link PagedFlux} |
yes that is what I replied to your earlier comment. You don't need to pass it but there is no harm in passing it. But to keep consistency I removed it here. The page size is not configurable but we will follow the same strategy as we have in .net. I will look at it as I start implementing samples. | Mono<PagedResponse<String>> queryNextPage(String query, String nextLink, Context context) {
QuerySpecification querySpecification = new QuerySpecification();
querySpecification
.setQuery(query)
.setContinuationToken(nextLink);
return protocolLayer
.getQueries()
.queryTwinsWithResponseAsync(querySpecification, context)
.map(objectPagedResponse -> new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
objectPagedResponse.getValue().getItems().stream()
.map(object -> {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.error("JsonProcessingException occurred while retrieving query result items: ", e);
throw new RuntimeException("JsonProcessingException occurred while retrieving query result items", e);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList()),
objectPagedResponse.getValue().getContinuationToken(),
objectPagedResponse.getDeserializedHeaders()));
} | .setQuery(query) | new QuerySpecification().setQuery(query);
return protocolLayer
.getQueries()
.queryTwinsWithResponseAsync(querySpecification, context)
.map(objectPagedResponse -> new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
objectPagedResponse.getValue().getItems().stream()
.map(object -> {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.error("JsonProcessingException occurred while retrieving query result items: ", e);
throw new RuntimeException("JsonProcessingException occurred while retrieving query result items", e);
}
} | class to convert the query response to.
* @param <T> The generic type to convert the query response to.
* @return A {@link PagedFlux} | class to convert the query response to.
* @param <T> The generic type to convert the query response to.
* @return A {@link PagedFlux} |
This can be `return query(query, Context.NONE)` instead. We can call the sync overload directly, instead of calling the async overload and creating a new PagedIterable. | public PagedIterable<String> query(String query) {
return new PagedIterable<>(digitalTwinsAsyncClient.query(query, Context.NONE));
} | return new PagedIterable<>(digitalTwinsAsyncClient.query(query, Context.NONE)); | public PagedIterable<String> query(String query) {
return query(query, Context.NONE);
} | class to deserialize the application/json component into.
* @param <T> The generic type to deserialize the component to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link DigitalTwinsResponse} | class to deserialize the application/json component into.
* @param <T> The generic type to deserialize the component to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link DigitalTwinsResponse} |
Nit: `validSharedKey` sounds like the shared key value is valid to the service. Suggest something like "includesSharedKeyValue" | public ConnectionStringProperties(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw new IllegalArgumentException("'connectionString' cannot be an empty string.");
}
final String[] tokenValuePairs = connectionString.split(TOKEN_VALUE_PAIR_DELIMITER);
URI endpoint = null;
String entityPath = null;
String sharedAccessKeyName = null;
String sharedAccessKeyValue = null;
String sharedAccessSignature = null;
for (String tokenValuePair : tokenValuePairs) {
final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2);
if (pair.length != 2) {
throw new IllegalArgumentException(String.format(
Locale.US,
"Connection string has invalid key value pair: %s",
tokenValuePair));
}
final String key = pair[0].trim();
final String value = pair[1].trim();
if (key.equalsIgnoreCase(ENDPOINT)) {
final String endpointUri = validateAndUpdateDefaultScheme(value, connectionString);
try {
endpoint = new URI(endpointUri);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(
String.format(Locale.US, "Invalid endpoint: %s", tokenValuePair), e);
}
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY_NAME)) {
sharedAccessKeyName = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY)) {
sharedAccessKeyValue = value;
} else if (key.equalsIgnoreCase(ENTITY_PATH)) {
entityPath = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_SIGNATURE)
&& value.toLowerCase(Locale.getDefault()).startsWith(SAS_VALUE_PREFIX)) {
sharedAccessSignature = value;
} else {
throw new IllegalArgumentException(
String.format(Locale.US, "Illegal connection string parameter name: %s", key));
}
}
boolean includesSharedKey = sharedAccessKeyName != null || sharedAccessKeyValue != null;
boolean validSharedKey = sharedAccessKeyName != null && sharedAccessKeyValue != null;
boolean includesSharedAccessSignature = sharedAccessSignature != null;
if (endpoint == null
|| (includesSharedKey && includesSharedAccessSignature)
|| (!validSharedKey && !includesSharedAccessSignature)) {
throw new IllegalArgumentException(String.format(Locale.US, ERROR_MESSAGE_FORMAT, connectionString));
}
this.endpoint = endpoint;
this.entityPath = entityPath;
this.sharedAccessKeyName = sharedAccessKeyName;
this.sharedAccessKey = sharedAccessKeyValue;
this.sharedAccessSignature = sharedAccessSignature;
} | boolean validSharedKey = sharedAccessKeyName != null && sharedAccessKeyValue != null; | public ConnectionStringProperties(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw new IllegalArgumentException("'connectionString' cannot be an empty string.");
}
final String[] tokenValuePairs = connectionString.split(TOKEN_VALUE_PAIR_DELIMITER);
URI endpoint = null;
String entityPath = null;
String sharedAccessKeyName = null;
String sharedAccessKeyValue = null;
String sharedAccessSignature = null;
for (String tokenValuePair : tokenValuePairs) {
final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2);
if (pair.length != 2) {
throw new IllegalArgumentException(String.format(
Locale.US,
"Connection string has invalid key value pair: %s",
tokenValuePair));
}
final String key = pair[0].trim();
final String value = pair[1].trim();
if (key.equalsIgnoreCase(ENDPOINT)) {
final String endpointUri = validateAndUpdateDefaultScheme(value, connectionString);
try {
endpoint = new URI(endpointUri);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(
String.format(Locale.US, "Invalid endpoint: %s", tokenValuePair), e);
}
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY_NAME)) {
sharedAccessKeyName = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY)) {
sharedAccessKeyValue = value;
} else if (key.equalsIgnoreCase(ENTITY_PATH)) {
entityPath = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_SIGNATURE)
&& value.toLowerCase(Locale.ROOT).startsWith(SAS_VALUE_PREFIX)) {
sharedAccessSignature = value;
} else {
throw new IllegalArgumentException(
String.format(Locale.US, "Illegal connection string parameter name: %s", key));
}
}
boolean includesSharedKey = sharedAccessKeyName != null || sharedAccessKeyValue != null;
boolean hasSharedKeyAndValue = sharedAccessKeyName != null && sharedAccessKeyValue != null;
boolean includesSharedAccessSignature = sharedAccessSignature != null;
if (endpoint == null
|| (includesSharedKey && includesSharedAccessSignature)
|| (!hasSharedKeyAndValue && !includesSharedAccessSignature)) {
throw new IllegalArgumentException(String.format(Locale.US, ERROR_MESSAGE_FORMAT, connectionString));
}
this.endpoint = endpoint;
this.entityPath = entityPath;
this.sharedAccessKeyName = sharedAccessKeyName;
this.sharedAccessKey = sharedAccessKeyValue;
this.sharedAccessSignature = sharedAccessSignature;
} | class ConnectionStringProperties {
private final ClientLogger logger = new ClientLogger(ConnectionStringProperties.class);
private static final String TOKEN_VALUE_SEPARATOR = "=";
private static final String ENDPOINT_SCHEME_SB_PREFIX = "sb:
private static final String ENDPOINT_SCHEME_HTTP_PREFIX = "http:
private static final String ENDPOINT_SCHEME_HTTPS_PREFIX = "https:
private static final String TOKEN_VALUE_PAIR_DELIMITER = ";";
private static final String ENDPOINT = "Endpoint";
private static final String SHARED_ACCESS_KEY_NAME = "SharedAccessKeyName";
private static final String SHARED_ACCESS_KEY = "SharedAccessKey";
private static final String SHARED_ACCESS_SIGNATURE = "SharedAccessSignature";
private static final String SAS_VALUE_PREFIX = "sharedaccesssignature ";
private static final String ENTITY_PATH = "EntityPath";
private static final String CS_WITH_ACCESS_KEY = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
+ "SharedAccessKey={sharedAccessKey};EntityPath={entityPath}";
private static final String CS_WITH_SAS = "Endpoint={endpoint};SharedAccessSignature="
+ "SharedAccessSignature {sharedAccessSignature}";
private static final String ERROR_MESSAGE_FORMAT = "Could not parse 'connectionString'. Expected format: "
+ CS_WITH_ACCESS_KEY + " or " + CS_WITH_SAS + ". Actual: %s";
private static final String ERROR_MESSAGE_ENDPOINT_FORMAT = "'Endpoint' must be provided in 'connectionString'."
+ " Actual: %s";
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private final String sharedAccessSignature;
/**
* Creates a new instance by parsing the {@code connectionString} into its components.
* @param connectionString The connection string to the Event Hub instance.
*
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if {@code connectionString} is an empty string or the connection string has
* an invalid format.
*/
/**
* Gets the endpoint to be used for connecting to the AMQP message broker.
* @return The endpoint address, including protocol, from the connection string.
*/
public URI getEndpoint() {
return endpoint;
}
/**
* Gets the entity path to connect to in the message broker.
* @return The entity path to connect to in the message broker.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the name of the shared access key, either for the Event Hubs namespace or the Event Hub instance.
* @return The name of the shared access key.
*/
public String getSharedAccessKeyName() {
return sharedAccessKeyName;
}
/**
* The value of the shared access key, either for the Event Hubs namespace or the Event Hub.
* @return The value of the shared access key.
*/
public String getSharedAccessKey() {
return sharedAccessKey;
}
/**
* The value of the shared access signature, if the connection string used to create this instance included the
* shared access signature component.
* @return The shared access signature value, if included in the connection string.
*/
public String getSharedAccessSignature() {
return sharedAccessSignature;
}
/*
* The function checks for pre existing scheme of "sb:
* in endpoint, it will set the default scheme to "sb:
*/
private String validateAndUpdateDefaultScheme(final String endpoint, final String connectionString) {
String updatedEndpoint = endpoint.trim();
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
ERROR_MESSAGE_ENDPOINT_FORMAT, connectionString)));
}
final String endpointLowerCase = endpoint.toLowerCase(Locale.getDefault());
if (!endpointLowerCase.startsWith(ENDPOINT_SCHEME_SB_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTP_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTPS_PREFIX)) {
updatedEndpoint = ENDPOINT_SCHEME_SB_PREFIX + endpoint;
}
return updatedEndpoint;
}
} | class ConnectionStringProperties {
private final ClientLogger logger = new ClientLogger(ConnectionStringProperties.class);
private static final String TOKEN_VALUE_SEPARATOR = "=";
private static final String ENDPOINT_SCHEME_SB_PREFIX = "sb:
private static final String ENDPOINT_SCHEME_HTTP_PREFIX = "http:
private static final String ENDPOINT_SCHEME_HTTPS_PREFIX = "https:
private static final String TOKEN_VALUE_PAIR_DELIMITER = ";";
private static final String ENDPOINT = "Endpoint";
private static final String SHARED_ACCESS_KEY_NAME = "SharedAccessKeyName";
private static final String SHARED_ACCESS_KEY = "SharedAccessKey";
private static final String SHARED_ACCESS_SIGNATURE = "SharedAccessSignature";
private static final String SAS_VALUE_PREFIX = "sharedaccesssignature ";
private static final String ENTITY_PATH = "EntityPath";
private static final String CONNECTION_STRING_WITH_ACCESS_KEY = "Endpoint={endpoint};"
+ "SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={entityPath}";
private static final String CONNECTION_STRING_WITH_SAS = "Endpoint={endpoint};SharedAccessSignature="
+ "SharedAccessSignature {sharedAccessSignature};EntityPath={entityPath}";
private static final String ERROR_MESSAGE_FORMAT = "Could not parse 'connectionString'. Expected format: "
+ CONNECTION_STRING_WITH_ACCESS_KEY + " or " + CONNECTION_STRING_WITH_SAS + ". Actual: %s";
private static final String ERROR_MESSAGE_ENDPOINT_FORMAT = "'Endpoint' must be provided in 'connectionString'."
+ " Actual: %s";
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private final String sharedAccessSignature;
/**
* Creates a new instance by parsing the {@code connectionString} into its components.
* @param connectionString The connection string to the Event Hub instance.
*
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if {@code connectionString} is an empty string or the connection string has
* an invalid format.
*/
/**
* Gets the endpoint to be used for connecting to the AMQP message broker.
* @return The endpoint address, including protocol, from the connection string.
*/
public URI getEndpoint() {
return endpoint;
}
/**
* Gets the entity path to connect to in the message broker.
* @return The entity path to connect to in the message broker.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the name of the shared access key, either for the Event Hubs namespace or the Event Hub instance.
* @return The name of the shared access key.
*/
public String getSharedAccessKeyName() {
return sharedAccessKeyName;
}
/**
* The value of the shared access key, either for the Event Hubs namespace or the Event Hub.
* @return The value of the shared access key.
*/
public String getSharedAccessKey() {
return sharedAccessKey;
}
/**
* The value of the shared access signature, if the connection string used to create this instance included the
* shared access signature component.
* @return The shared access signature value, if included in the connection string.
*/
public String getSharedAccessSignature() {
return sharedAccessSignature;
}
/*
* The function checks for pre existing scheme of "sb:
* in endpoint, it will set the default scheme to "sb:
*/
private String validateAndUpdateDefaultScheme(final String endpoint, final String connectionString) {
String updatedEndpoint = endpoint.trim();
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
ERROR_MESSAGE_ENDPOINT_FORMAT, connectionString)));
}
final String endpointLowerCase = endpoint.toLowerCase(Locale.getDefault());
if (!endpointLowerCase.startsWith(ENDPOINT_SCHEME_SB_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTP_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTPS_PREFIX)) {
updatedEndpoint = ENDPOINT_SCHEME_SB_PREFIX + endpoint;
}
return updatedEndpoint;
}
} |
Using constructor overloads work well. How about using a different sub class of `TokenCredential`, like `EventHubSharedAccessSignatureCredential`, or the shorter version `EventHubSASCredential`? It's cleaner to user two separate classes. Maybe someday the shared access signature will support new behaviors like token renew. | private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
} | tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); | private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer,
product, clientVersion);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions,
proxyOptions, scheduler);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer,
product, clientVersion);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions,
proxyOptions, scheduler);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} |
This is similar to what .NET is doing. I am not sure we should introduce too many credential types when the token returned for both types of connection strings are the same. | private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
} | tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); | private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer,
product, clientVersion);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions,
proxyOptions, scheduler);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer,
product, clientVersion);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions,
proxyOptions, scheduler);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} |
Updated name to `hasSharedKeyAndValue`. | public ConnectionStringProperties(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw new IllegalArgumentException("'connectionString' cannot be an empty string.");
}
final String[] tokenValuePairs = connectionString.split(TOKEN_VALUE_PAIR_DELIMITER);
URI endpoint = null;
String entityPath = null;
String sharedAccessKeyName = null;
String sharedAccessKeyValue = null;
String sharedAccessSignature = null;
for (String tokenValuePair : tokenValuePairs) {
final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2);
if (pair.length != 2) {
throw new IllegalArgumentException(String.format(
Locale.US,
"Connection string has invalid key value pair: %s",
tokenValuePair));
}
final String key = pair[0].trim();
final String value = pair[1].trim();
if (key.equalsIgnoreCase(ENDPOINT)) {
final String endpointUri = validateAndUpdateDefaultScheme(value, connectionString);
try {
endpoint = new URI(endpointUri);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(
String.format(Locale.US, "Invalid endpoint: %s", tokenValuePair), e);
}
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY_NAME)) {
sharedAccessKeyName = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY)) {
sharedAccessKeyValue = value;
} else if (key.equalsIgnoreCase(ENTITY_PATH)) {
entityPath = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_SIGNATURE)
&& value.toLowerCase(Locale.getDefault()).startsWith(SAS_VALUE_PREFIX)) {
sharedAccessSignature = value;
} else {
throw new IllegalArgumentException(
String.format(Locale.US, "Illegal connection string parameter name: %s", key));
}
}
boolean includesSharedKey = sharedAccessKeyName != null || sharedAccessKeyValue != null;
boolean validSharedKey = sharedAccessKeyName != null && sharedAccessKeyValue != null;
boolean includesSharedAccessSignature = sharedAccessSignature != null;
if (endpoint == null
|| (includesSharedKey && includesSharedAccessSignature)
|| (!validSharedKey && !includesSharedAccessSignature)) {
throw new IllegalArgumentException(String.format(Locale.US, ERROR_MESSAGE_FORMAT, connectionString));
}
this.endpoint = endpoint;
this.entityPath = entityPath;
this.sharedAccessKeyName = sharedAccessKeyName;
this.sharedAccessKey = sharedAccessKeyValue;
this.sharedAccessSignature = sharedAccessSignature;
} | boolean validSharedKey = sharedAccessKeyName != null && sharedAccessKeyValue != null; | public ConnectionStringProperties(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw new IllegalArgumentException("'connectionString' cannot be an empty string.");
}
final String[] tokenValuePairs = connectionString.split(TOKEN_VALUE_PAIR_DELIMITER);
URI endpoint = null;
String entityPath = null;
String sharedAccessKeyName = null;
String sharedAccessKeyValue = null;
String sharedAccessSignature = null;
for (String tokenValuePair : tokenValuePairs) {
final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2);
if (pair.length != 2) {
throw new IllegalArgumentException(String.format(
Locale.US,
"Connection string has invalid key value pair: %s",
tokenValuePair));
}
final String key = pair[0].trim();
final String value = pair[1].trim();
if (key.equalsIgnoreCase(ENDPOINT)) {
final String endpointUri = validateAndUpdateDefaultScheme(value, connectionString);
try {
endpoint = new URI(endpointUri);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(
String.format(Locale.US, "Invalid endpoint: %s", tokenValuePair), e);
}
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY_NAME)) {
sharedAccessKeyName = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY)) {
sharedAccessKeyValue = value;
} else if (key.equalsIgnoreCase(ENTITY_PATH)) {
entityPath = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_SIGNATURE)
&& value.toLowerCase(Locale.ROOT).startsWith(SAS_VALUE_PREFIX)) {
sharedAccessSignature = value;
} else {
throw new IllegalArgumentException(
String.format(Locale.US, "Illegal connection string parameter name: %s", key));
}
}
boolean includesSharedKey = sharedAccessKeyName != null || sharedAccessKeyValue != null;
boolean hasSharedKeyAndValue = sharedAccessKeyName != null && sharedAccessKeyValue != null;
boolean includesSharedAccessSignature = sharedAccessSignature != null;
if (endpoint == null
|| (includesSharedKey && includesSharedAccessSignature)
|| (!hasSharedKeyAndValue && !includesSharedAccessSignature)) {
throw new IllegalArgumentException(String.format(Locale.US, ERROR_MESSAGE_FORMAT, connectionString));
}
this.endpoint = endpoint;
this.entityPath = entityPath;
this.sharedAccessKeyName = sharedAccessKeyName;
this.sharedAccessKey = sharedAccessKeyValue;
this.sharedAccessSignature = sharedAccessSignature;
} | class ConnectionStringProperties {
private final ClientLogger logger = new ClientLogger(ConnectionStringProperties.class);
private static final String TOKEN_VALUE_SEPARATOR = "=";
private static final String ENDPOINT_SCHEME_SB_PREFIX = "sb:
private static final String ENDPOINT_SCHEME_HTTP_PREFIX = "http:
private static final String ENDPOINT_SCHEME_HTTPS_PREFIX = "https:
private static final String TOKEN_VALUE_PAIR_DELIMITER = ";";
private static final String ENDPOINT = "Endpoint";
private static final String SHARED_ACCESS_KEY_NAME = "SharedAccessKeyName";
private static final String SHARED_ACCESS_KEY = "SharedAccessKey";
private static final String SHARED_ACCESS_SIGNATURE = "SharedAccessSignature";
private static final String SAS_VALUE_PREFIX = "sharedaccesssignature ";
private static final String ENTITY_PATH = "EntityPath";
private static final String CS_WITH_ACCESS_KEY = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
+ "SharedAccessKey={sharedAccessKey};EntityPath={entityPath}";
private static final String CS_WITH_SAS = "Endpoint={endpoint};SharedAccessSignature="
+ "SharedAccessSignature {sharedAccessSignature}";
private static final String ERROR_MESSAGE_FORMAT = "Could not parse 'connectionString'. Expected format: "
+ CS_WITH_ACCESS_KEY + " or " + CS_WITH_SAS + ". Actual: %s";
private static final String ERROR_MESSAGE_ENDPOINT_FORMAT = "'Endpoint' must be provided in 'connectionString'."
+ " Actual: %s";
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private final String sharedAccessSignature;
/**
* Creates a new instance by parsing the {@code connectionString} into its components.
* @param connectionString The connection string to the Event Hub instance.
*
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if {@code connectionString} is an empty string or the connection string has
* an invalid format.
*/
/**
* Gets the endpoint to be used for connecting to the AMQP message broker.
* @return The endpoint address, including protocol, from the connection string.
*/
public URI getEndpoint() {
return endpoint;
}
/**
* Gets the entity path to connect to in the message broker.
* @return The entity path to connect to in the message broker.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the name of the shared access key, either for the Event Hubs namespace or the Event Hub instance.
* @return The name of the shared access key.
*/
public String getSharedAccessKeyName() {
return sharedAccessKeyName;
}
/**
* The value of the shared access key, either for the Event Hubs namespace or the Event Hub.
* @return The value of the shared access key.
*/
public String getSharedAccessKey() {
return sharedAccessKey;
}
/**
* The value of the shared access signature, if the connection string used to create this instance included the
* shared access signature component.
* @return The shared access signature value, if included in the connection string.
*/
public String getSharedAccessSignature() {
return sharedAccessSignature;
}
/*
* The function checks for pre existing scheme of "sb:
* in endpoint, it will set the default scheme to "sb:
*/
private String validateAndUpdateDefaultScheme(final String endpoint, final String connectionString) {
String updatedEndpoint = endpoint.trim();
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
ERROR_MESSAGE_ENDPOINT_FORMAT, connectionString)));
}
final String endpointLowerCase = endpoint.toLowerCase(Locale.getDefault());
if (!endpointLowerCase.startsWith(ENDPOINT_SCHEME_SB_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTP_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTPS_PREFIX)) {
updatedEndpoint = ENDPOINT_SCHEME_SB_PREFIX + endpoint;
}
return updatedEndpoint;
}
} | class ConnectionStringProperties {
private final ClientLogger logger = new ClientLogger(ConnectionStringProperties.class);
private static final String TOKEN_VALUE_SEPARATOR = "=";
private static final String ENDPOINT_SCHEME_SB_PREFIX = "sb:
private static final String ENDPOINT_SCHEME_HTTP_PREFIX = "http:
private static final String ENDPOINT_SCHEME_HTTPS_PREFIX = "https:
private static final String TOKEN_VALUE_PAIR_DELIMITER = ";";
private static final String ENDPOINT = "Endpoint";
private static final String SHARED_ACCESS_KEY_NAME = "SharedAccessKeyName";
private static final String SHARED_ACCESS_KEY = "SharedAccessKey";
private static final String SHARED_ACCESS_SIGNATURE = "SharedAccessSignature";
private static final String SAS_VALUE_PREFIX = "sharedaccesssignature ";
private static final String ENTITY_PATH = "EntityPath";
private static final String CONNECTION_STRING_WITH_ACCESS_KEY = "Endpoint={endpoint};"
+ "SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={entityPath}";
private static final String CONNECTION_STRING_WITH_SAS = "Endpoint={endpoint};SharedAccessSignature="
+ "SharedAccessSignature {sharedAccessSignature};EntityPath={entityPath}";
private static final String ERROR_MESSAGE_FORMAT = "Could not parse 'connectionString'. Expected format: "
+ CONNECTION_STRING_WITH_ACCESS_KEY + " or " + CONNECTION_STRING_WITH_SAS + ". Actual: %s";
private static final String ERROR_MESSAGE_ENDPOINT_FORMAT = "'Endpoint' must be provided in 'connectionString'."
+ " Actual: %s";
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private final String sharedAccessSignature;
/**
* Creates a new instance by parsing the {@code connectionString} into its components.
* @param connectionString The connection string to the Event Hub instance.
*
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if {@code connectionString} is an empty string or the connection string has
* an invalid format.
*/
/**
* Gets the endpoint to be used for connecting to the AMQP message broker.
* @return The endpoint address, including protocol, from the connection string.
*/
public URI getEndpoint() {
return endpoint;
}
/**
* Gets the entity path to connect to in the message broker.
* @return The entity path to connect to in the message broker.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the name of the shared access key, either for the Event Hubs namespace or the Event Hub instance.
* @return The name of the shared access key.
*/
public String getSharedAccessKeyName() {
return sharedAccessKeyName;
}
/**
* The value of the shared access key, either for the Event Hubs namespace or the Event Hub.
* @return The value of the shared access key.
*/
public String getSharedAccessKey() {
return sharedAccessKey;
}
/**
* The value of the shared access signature, if the connection string used to create this instance included the
* shared access signature component.
* @return The shared access signature value, if included in the connection string.
*/
public String getSharedAccessSignature() {
return sharedAccessSignature;
}
/*
* The function checks for pre existing scheme of "sb:
* in endpoint, it will set the default scheme to "sb:
*/
private String validateAndUpdateDefaultScheme(final String endpoint, final String connectionString) {
String updatedEndpoint = endpoint.trim();
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
ERROR_MESSAGE_ENDPOINT_FORMAT, connectionString)));
}
final String endpointLowerCase = endpoint.toLowerCase(Locale.getDefault());
if (!endpointLowerCase.startsWith(ENDPOINT_SCHEME_SB_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTP_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTPS_PREFIX)) {
updatedEndpoint = ENDPOINT_SCHEME_SB_PREFIX + endpoint;
}
return updatedEndpoint;
}
} |
This value should be culture agnostic, I would use the culture invariant locale. | public ConnectionStringProperties(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw new IllegalArgumentException("'connectionString' cannot be an empty string.");
}
final String[] tokenValuePairs = connectionString.split(TOKEN_VALUE_PAIR_DELIMITER);
URI endpoint = null;
String entityPath = null;
String sharedAccessKeyName = null;
String sharedAccessKeyValue = null;
String sharedAccessSignature = null;
for (String tokenValuePair : tokenValuePairs) {
final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2);
if (pair.length != 2) {
throw new IllegalArgumentException(String.format(
Locale.US,
"Connection string has invalid key value pair: %s",
tokenValuePair));
}
final String key = pair[0].trim();
final String value = pair[1].trim();
if (key.equalsIgnoreCase(ENDPOINT)) {
final String endpointUri = validateAndUpdateDefaultScheme(value, connectionString);
try {
endpoint = new URI(endpointUri);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(
String.format(Locale.US, "Invalid endpoint: %s", tokenValuePair), e);
}
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY_NAME)) {
sharedAccessKeyName = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY)) {
sharedAccessKeyValue = value;
} else if (key.equalsIgnoreCase(ENTITY_PATH)) {
entityPath = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_SIGNATURE)
&& value.toLowerCase(Locale.getDefault()).startsWith(SAS_VALUE_PREFIX)) {
sharedAccessSignature = value;
} else {
throw new IllegalArgumentException(
String.format(Locale.US, "Illegal connection string parameter name: %s", key));
}
}
boolean includesSharedKey = sharedAccessKeyName != null || sharedAccessKeyValue != null;
boolean hasSharedKeyAndValue = sharedAccessKeyName != null && sharedAccessKeyValue != null;
boolean includesSharedAccessSignature = sharedAccessSignature != null;
if (endpoint == null
|| (includesSharedKey && includesSharedAccessSignature)
|| (!hasSharedKeyAndValue && !includesSharedAccessSignature)) {
throw new IllegalArgumentException(String.format(Locale.US, ERROR_MESSAGE_FORMAT, connectionString));
}
this.endpoint = endpoint;
this.entityPath = entityPath;
this.sharedAccessKeyName = sharedAccessKeyName;
this.sharedAccessKey = sharedAccessKeyValue;
this.sharedAccessSignature = sharedAccessSignature;
} | && value.toLowerCase(Locale.getDefault()).startsWith(SAS_VALUE_PREFIX)) { | public ConnectionStringProperties(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw new IllegalArgumentException("'connectionString' cannot be an empty string.");
}
final String[] tokenValuePairs = connectionString.split(TOKEN_VALUE_PAIR_DELIMITER);
URI endpoint = null;
String entityPath = null;
String sharedAccessKeyName = null;
String sharedAccessKeyValue = null;
String sharedAccessSignature = null;
for (String tokenValuePair : tokenValuePairs) {
final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2);
if (pair.length != 2) {
throw new IllegalArgumentException(String.format(
Locale.US,
"Connection string has invalid key value pair: %s",
tokenValuePair));
}
final String key = pair[0].trim();
final String value = pair[1].trim();
if (key.equalsIgnoreCase(ENDPOINT)) {
final String endpointUri = validateAndUpdateDefaultScheme(value, connectionString);
try {
endpoint = new URI(endpointUri);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(
String.format(Locale.US, "Invalid endpoint: %s", tokenValuePair), e);
}
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY_NAME)) {
sharedAccessKeyName = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY)) {
sharedAccessKeyValue = value;
} else if (key.equalsIgnoreCase(ENTITY_PATH)) {
entityPath = value;
} else if (key.equalsIgnoreCase(SHARED_ACCESS_SIGNATURE)
&& value.toLowerCase(Locale.ROOT).startsWith(SAS_VALUE_PREFIX)) {
sharedAccessSignature = value;
} else {
throw new IllegalArgumentException(
String.format(Locale.US, "Illegal connection string parameter name: %s", key));
}
}
boolean includesSharedKey = sharedAccessKeyName != null || sharedAccessKeyValue != null;
boolean hasSharedKeyAndValue = sharedAccessKeyName != null && sharedAccessKeyValue != null;
boolean includesSharedAccessSignature = sharedAccessSignature != null;
if (endpoint == null
|| (includesSharedKey && includesSharedAccessSignature)
|| (!hasSharedKeyAndValue && !includesSharedAccessSignature)) {
throw new IllegalArgumentException(String.format(Locale.US, ERROR_MESSAGE_FORMAT, connectionString));
}
this.endpoint = endpoint;
this.entityPath = entityPath;
this.sharedAccessKeyName = sharedAccessKeyName;
this.sharedAccessKey = sharedAccessKeyValue;
this.sharedAccessSignature = sharedAccessSignature;
} | class ConnectionStringProperties {
private final ClientLogger logger = new ClientLogger(ConnectionStringProperties.class);
private static final String TOKEN_VALUE_SEPARATOR = "=";
private static final String ENDPOINT_SCHEME_SB_PREFIX = "sb:
private static final String ENDPOINT_SCHEME_HTTP_PREFIX = "http:
private static final String ENDPOINT_SCHEME_HTTPS_PREFIX = "https:
private static final String TOKEN_VALUE_PAIR_DELIMITER = ";";
private static final String ENDPOINT = "Endpoint";
private static final String SHARED_ACCESS_KEY_NAME = "SharedAccessKeyName";
private static final String SHARED_ACCESS_KEY = "SharedAccessKey";
private static final String SHARED_ACCESS_SIGNATURE = "SharedAccessSignature";
private static final String SAS_VALUE_PREFIX = "sharedaccesssignature ";
private static final String ENTITY_PATH = "EntityPath";
private static final String CS_WITH_ACCESS_KEY = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
+ "SharedAccessKey={sharedAccessKey};EntityPath={entityPath}";
private static final String CS_WITH_SAS = "Endpoint={endpoint};SharedAccessSignature="
+ "SharedAccessSignature {sharedAccessSignature};EntityPath={entityPath}";
private static final String ERROR_MESSAGE_FORMAT = "Could not parse 'connectionString'. Expected format: "
+ CS_WITH_ACCESS_KEY + " or " + CS_WITH_SAS + ". Actual: %s";
private static final String ERROR_MESSAGE_ENDPOINT_FORMAT = "'Endpoint' must be provided in 'connectionString'."
+ " Actual: %s";
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private final String sharedAccessSignature;
/**
* Creates a new instance by parsing the {@code connectionString} into its components.
* @param connectionString The connection string to the Event Hub instance.
*
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if {@code connectionString} is an empty string or the connection string has
* an invalid format.
*/
/**
* Gets the endpoint to be used for connecting to the AMQP message broker.
* @return The endpoint address, including protocol, from the connection string.
*/
public URI getEndpoint() {
return endpoint;
}
/**
* Gets the entity path to connect to in the message broker.
* @return The entity path to connect to in the message broker.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the name of the shared access key, either for the Event Hubs namespace or the Event Hub instance.
* @return The name of the shared access key.
*/
public String getSharedAccessKeyName() {
return sharedAccessKeyName;
}
/**
* The value of the shared access key, either for the Event Hubs namespace or the Event Hub.
* @return The value of the shared access key.
*/
public String getSharedAccessKey() {
return sharedAccessKey;
}
/**
* The value of the shared access signature, if the connection string used to create this instance included the
* shared access signature component.
* @return The shared access signature value, if included in the connection string.
*/
public String getSharedAccessSignature() {
return sharedAccessSignature;
}
/*
* The function checks for pre existing scheme of "sb:
* in endpoint, it will set the default scheme to "sb:
*/
private String validateAndUpdateDefaultScheme(final String endpoint, final String connectionString) {
String updatedEndpoint = endpoint.trim();
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
ERROR_MESSAGE_ENDPOINT_FORMAT, connectionString)));
}
final String endpointLowerCase = endpoint.toLowerCase(Locale.getDefault());
if (!endpointLowerCase.startsWith(ENDPOINT_SCHEME_SB_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTP_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTPS_PREFIX)) {
updatedEndpoint = ENDPOINT_SCHEME_SB_PREFIX + endpoint;
}
return updatedEndpoint;
}
} | class ConnectionStringProperties {
private final ClientLogger logger = new ClientLogger(ConnectionStringProperties.class);
private static final String TOKEN_VALUE_SEPARATOR = "=";
private static final String ENDPOINT_SCHEME_SB_PREFIX = "sb:
private static final String ENDPOINT_SCHEME_HTTP_PREFIX = "http:
private static final String ENDPOINT_SCHEME_HTTPS_PREFIX = "https:
private static final String TOKEN_VALUE_PAIR_DELIMITER = ";";
private static final String ENDPOINT = "Endpoint";
private static final String SHARED_ACCESS_KEY_NAME = "SharedAccessKeyName";
private static final String SHARED_ACCESS_KEY = "SharedAccessKey";
private static final String SHARED_ACCESS_SIGNATURE = "SharedAccessSignature";
private static final String SAS_VALUE_PREFIX = "sharedaccesssignature ";
private static final String ENTITY_PATH = "EntityPath";
private static final String CONNECTION_STRING_WITH_ACCESS_KEY = "Endpoint={endpoint};"
+ "SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={entityPath}";
private static final String CONNECTION_STRING_WITH_SAS = "Endpoint={endpoint};SharedAccessSignature="
+ "SharedAccessSignature {sharedAccessSignature};EntityPath={entityPath}";
private static final String ERROR_MESSAGE_FORMAT = "Could not parse 'connectionString'. Expected format: "
+ CONNECTION_STRING_WITH_ACCESS_KEY + " or " + CONNECTION_STRING_WITH_SAS + ". Actual: %s";
private static final String ERROR_MESSAGE_ENDPOINT_FORMAT = "'Endpoint' must be provided in 'connectionString'."
+ " Actual: %s";
private final URI endpoint;
private final String entityPath;
private final String sharedAccessKeyName;
private final String sharedAccessKey;
private final String sharedAccessSignature;
/**
* Creates a new instance by parsing the {@code connectionString} into its components.
* @param connectionString The connection string to the Event Hub instance.
*
* @throws NullPointerException if {@code connectionString} is null.
* @throws IllegalArgumentException if {@code connectionString} is an empty string or the connection string has
* an invalid format.
*/
/**
* Gets the endpoint to be used for connecting to the AMQP message broker.
* @return The endpoint address, including protocol, from the connection string.
*/
public URI getEndpoint() {
return endpoint;
}
/**
* Gets the entity path to connect to in the message broker.
* @return The entity path to connect to in the message broker.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Gets the name of the shared access key, either for the Event Hubs namespace or the Event Hub instance.
* @return The name of the shared access key.
*/
public String getSharedAccessKeyName() {
return sharedAccessKeyName;
}
/**
* The value of the shared access key, either for the Event Hubs namespace or the Event Hub.
* @return The value of the shared access key.
*/
public String getSharedAccessKey() {
return sharedAccessKey;
}
/**
* The value of the shared access signature, if the connection string used to create this instance included the
* shared access signature component.
* @return The shared access signature value, if included in the connection string.
*/
public String getSharedAccessSignature() {
return sharedAccessSignature;
}
/*
* The function checks for pre existing scheme of "sb:
* in endpoint, it will set the default scheme to "sb:
*/
private String validateAndUpdateDefaultScheme(final String endpoint, final String connectionString) {
String updatedEndpoint = endpoint.trim();
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
ERROR_MESSAGE_ENDPOINT_FORMAT, connectionString)));
}
final String endpointLowerCase = endpoint.toLowerCase(Locale.getDefault());
if (!endpointLowerCase.startsWith(ENDPOINT_SCHEME_SB_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTP_PREFIX)
&& !endpointLowerCase.startsWith(ENDPOINT_SCHEME_HTTPS_PREFIX)) {
updatedEndpoint = ENDPOINT_SCHEME_SB_PREFIX + endpoint;
}
return updatedEndpoint;
}
} |
This is all internal. So I don't have very strong opinion to use separate classes. Let's go ahead with this. | private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
} | tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); | private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer,
product, clientVersion);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions,
proxyOptions, scheduler);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer,
product, clientVersion);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions,
proxyOptions, scheduler);
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} |
Any possibility that `logOptions` is `null`? | private static UserAgentPolicy getUserAgentPolicy(Configuration configuration, HttpLogOptions logOptions) {
configuration = (configuration == null) ? Configuration.NONE : configuration;
String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(logOptions.getApplicationId(), clientName, clientVersion,
configuration);
} | return new UserAgentPolicy(logOptions.getApplicationId(), clientName, clientVersion, | private static UserAgentPolicy getUserAgentPolicy(Configuration configuration, HttpLogOptions logOptions) {
configuration = (configuration == null) ? Configuration.NONE : configuration;
String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(logOptions.getApplicationId(), clientName, clientVersion,
configuration);
} | class BuilderHelper {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-storage-blob.properties");
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Constructs a {@link HttpPipeline} from values passed from a builder.
*
* @param storageSharedKeyCredential {@link StorageSharedKeyCredential} if present.
* @param tokenCredential {@link TokenCredential} if present.
* @param sasTokenCredential {@link SasTokenCredential} if present.
* @param endpoint The endpoint for the client.
* @param retryOptions Retry options to set in the retry policy.
* @param logOptions Logging options to set in the logging policy.
* @param httpClient HttpClient to use in the builder.
* @param additionalPolicies Additional {@link HttpPipelinePolicy policies} to set in the pipeline.
* @param configuration Configuration store contain environment settings.
* @param logger {@link ClientLogger} used to log any exception.
* @return A new {@link HttpPipeline} from the passed values.
*/
public static HttpPipeline buildPipeline(StorageSharedKeyCredential storageSharedKeyCredential,
TokenCredential tokenCredential, SasTokenCredential sasTokenCredential, String endpoint,
RequestRetryOptions retryOptions, HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, Configuration configuration, ClientLogger logger) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(getUserAgentPolicy(configuration, logOptions));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(new RequestRetryPolicy(retryOptions));
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy;
if (storageSharedKeyCredential != null) {
credentialPolicy = new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential);
} else if (tokenCredential != null) {
httpsValidation(tokenCredential, "bearer token", endpoint, logger);
credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential,
String.format("%s/.default", getPrimaryEndpointForTokenAuth(endpoint)));
} else if (sasTokenCredential != null) {
credentialPolicy = new SasTokenCredentialPolicy(sasTokenCredential);
} else {
credentialPolicy = null;
}
if (credentialPolicy != null) {
policies.add(credentialPolicy);
}
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(getResponseValidationPolicy());
policies.add(new HttpLoggingPolicy(logOptions));
policies.add(new ScrubEtagPolicy());
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
*
* @param endpoint The endpoint passed by the customer.
* @return The primary endpoint for the account. It may be the same endpoint passed if it is already a primary or it
* may have had "-secondary" stripped from the end of the account name.
*/
private static String getPrimaryEndpointForTokenAuth(String endpoint) {
String[] parts = endpoint.split("\\.");
parts[0] = parts[0].endsWith("-secondary") ? parts[0].substring(0, parts[0].length() - "-secondary".length())
: parts[0];
return String.join(".", parts);
}
/**
* Gets the default http log option for Storage Blob.
*
* @return the default http log options.
*/
public static HttpLogOptions getDefaultHttpLogOptions() {
HttpLogOptions defaultOptions = new HttpLogOptions();
BlobHeadersAndQueryParameters.getBlobHeaders().forEach(defaultOptions::addAllowedHeaderName);
BlobHeadersAndQueryParameters.getBlobQueryParameters().forEach(defaultOptions::addAllowedQueryParamName);
return defaultOptions;
}
/**
* Gets the endpoint for the blob service based on the parsed URL.
*
* @param parts The {@link BlobUrlParts} from the parse URL.
* @return The endpoint for the blob service.
*/
public static String getEndpoint(BlobUrlParts parts) throws MalformedURLException {
if (ModelHelper.determineAuthorityIsIpStyle(parts.getHost())) {
return String.format("%s:
} else {
return String.format("%s:
}
}
/**
* Validates that the client is properly configured to use https.
*
* @param objectToCheck The object to check for.
* @param objectName The name of the object.
* @param endpoint The endpoint for the client.
*/
public static void httpsValidation(Object objectToCheck, String objectName, String endpoint, ClientLogger logger) {
if (objectToCheck != null && !BlobUrlParts.parse(endpoint).getScheme().equals(Constants.HTTPS)) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Using a(n) " + objectName + " requires https"));
}
}
/*
* Creates a {@link UserAgentPolicy} using the default blob module name and version.
*
* @param configuration Configuration store used to determine whether telemetry information should be included.
* @param logOptions Logging options to set in the logging policy.
* @return The default {@link UserAgentPolicy} for the module.
*/
/*
* Creates a {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} used to validate response data from
* the service.
*
* @return The {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} for the module.
*/
private static HttpPipelinePolicy getResponseValidationPolicy() {
return new ResponseValidationPolicyBuilder()
.addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID)
.addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256)
.build();
}
} | class BuilderHelper {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-storage-blob.properties");
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Constructs a {@link HttpPipeline} from values passed from a builder.
*
* @param storageSharedKeyCredential {@link StorageSharedKeyCredential} if present.
* @param tokenCredential {@link TokenCredential} if present.
* @param sasTokenCredential {@link SasTokenCredential} if present.
* @param endpoint The endpoint for the client.
* @param retryOptions Retry options to set in the retry policy.
* @param logOptions Logging options to set in the logging policy.
* @param httpClient HttpClient to use in the builder.
* @param additionalPolicies Additional {@link HttpPipelinePolicy policies} to set in the pipeline.
* @param configuration Configuration store contain environment settings.
* @param logger {@link ClientLogger} used to log any exception.
* @return A new {@link HttpPipeline} from the passed values.
*/
public static HttpPipeline buildPipeline(StorageSharedKeyCredential storageSharedKeyCredential,
TokenCredential tokenCredential, SasTokenCredential sasTokenCredential, String endpoint,
RequestRetryOptions retryOptions, HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, Configuration configuration, ClientLogger logger) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(getUserAgentPolicy(configuration, logOptions));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(new RequestRetryPolicy(retryOptions));
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy;
if (storageSharedKeyCredential != null) {
credentialPolicy = new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential);
} else if (tokenCredential != null) {
httpsValidation(tokenCredential, "bearer token", endpoint, logger);
credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential,
String.format("%s/.default", getPrimaryEndpointForTokenAuth(endpoint)));
} else if (sasTokenCredential != null) {
credentialPolicy = new SasTokenCredentialPolicy(sasTokenCredential);
} else {
credentialPolicy = null;
}
if (credentialPolicy != null) {
policies.add(credentialPolicy);
}
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(getResponseValidationPolicy());
policies.add(new HttpLoggingPolicy(logOptions));
policies.add(new ScrubEtagPolicy());
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
*
* @param endpoint The endpoint passed by the customer.
* @return The primary endpoint for the account. It may be the same endpoint passed if it is already a primary or it
* may have had "-secondary" stripped from the end of the account name.
*/
private static String getPrimaryEndpointForTokenAuth(String endpoint) {
String[] parts = endpoint.split("\\.");
parts[0] = parts[0].endsWith("-secondary") ? parts[0].substring(0, parts[0].length() - "-secondary".length())
: parts[0];
return String.join(".", parts);
}
/**
* Gets the default http log option for Storage Blob.
*
* @return the default http log options.
*/
public static HttpLogOptions getDefaultHttpLogOptions() {
HttpLogOptions defaultOptions = new HttpLogOptions();
BlobHeadersAndQueryParameters.getBlobHeaders().forEach(defaultOptions::addAllowedHeaderName);
BlobHeadersAndQueryParameters.getBlobQueryParameters().forEach(defaultOptions::addAllowedQueryParamName);
return defaultOptions;
}
/**
* Gets the endpoint for the blob service based on the parsed URL.
*
* @param parts The {@link BlobUrlParts} from the parse URL.
* @return The endpoint for the blob service.
*/
public static String getEndpoint(BlobUrlParts parts) throws MalformedURLException {
if (ModelHelper.determineAuthorityIsIpStyle(parts.getHost())) {
return String.format("%s:
} else {
return String.format("%s:
}
}
/**
* Validates that the client is properly configured to use https.
*
* @param objectToCheck The object to check for.
* @param objectName The name of the object.
* @param endpoint The endpoint for the client.
*/
public static void httpsValidation(Object objectToCheck, String objectName, String endpoint, ClientLogger logger) {
if (objectToCheck != null && !BlobUrlParts.parse(endpoint).getScheme().equals(Constants.HTTPS)) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Using a(n) " + objectName + " requires https"));
}
}
/*
* Creates a {@link UserAgentPolicy} using the default blob module name and version.
*
* @param configuration Configuration store used to determine whether telemetry information should be included.
* @param logOptions Logging options to set in the logging policy.
* @return The default {@link UserAgentPolicy} for the module.
*/
/*
* Creates a {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} used to validate response data from
* the service.
*
* @return The {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} for the module.
*/
private static HttpPipelinePolicy getResponseValidationPolicy() {
return new ResponseValidationPolicyBuilder()
.addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID)
.addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256)
.build();
}
} |
This method is only called by our builders where we set logOptions to default log options, so I think it is safe. | private static UserAgentPolicy getUserAgentPolicy(Configuration configuration, HttpLogOptions logOptions) {
configuration = (configuration == null) ? Configuration.NONE : configuration;
String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(logOptions.getApplicationId(), clientName, clientVersion,
configuration);
} | return new UserAgentPolicy(logOptions.getApplicationId(), clientName, clientVersion, | private static UserAgentPolicy getUserAgentPolicy(Configuration configuration, HttpLogOptions logOptions) {
configuration = (configuration == null) ? Configuration.NONE : configuration;
String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(logOptions.getApplicationId(), clientName, clientVersion,
configuration);
} | class BuilderHelper {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-storage-blob.properties");
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Constructs a {@link HttpPipeline} from values passed from a builder.
*
* @param storageSharedKeyCredential {@link StorageSharedKeyCredential} if present.
* @param tokenCredential {@link TokenCredential} if present.
* @param sasTokenCredential {@link SasTokenCredential} if present.
* @param endpoint The endpoint for the client.
* @param retryOptions Retry options to set in the retry policy.
* @param logOptions Logging options to set in the logging policy.
* @param httpClient HttpClient to use in the builder.
* @param additionalPolicies Additional {@link HttpPipelinePolicy policies} to set in the pipeline.
* @param configuration Configuration store contain environment settings.
* @param logger {@link ClientLogger} used to log any exception.
* @return A new {@link HttpPipeline} from the passed values.
*/
public static HttpPipeline buildPipeline(StorageSharedKeyCredential storageSharedKeyCredential,
TokenCredential tokenCredential, SasTokenCredential sasTokenCredential, String endpoint,
RequestRetryOptions retryOptions, HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, Configuration configuration, ClientLogger logger) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(getUserAgentPolicy(configuration, logOptions));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(new RequestRetryPolicy(retryOptions));
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy;
if (storageSharedKeyCredential != null) {
credentialPolicy = new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential);
} else if (tokenCredential != null) {
httpsValidation(tokenCredential, "bearer token", endpoint, logger);
credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential,
String.format("%s/.default", getPrimaryEndpointForTokenAuth(endpoint)));
} else if (sasTokenCredential != null) {
credentialPolicy = new SasTokenCredentialPolicy(sasTokenCredential);
} else {
credentialPolicy = null;
}
if (credentialPolicy != null) {
policies.add(credentialPolicy);
}
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(getResponseValidationPolicy());
policies.add(new HttpLoggingPolicy(logOptions));
policies.add(new ScrubEtagPolicy());
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
*
* @param endpoint The endpoint passed by the customer.
* @return The primary endpoint for the account. It may be the same endpoint passed if it is already a primary or it
* may have had "-secondary" stripped from the end of the account name.
*/
private static String getPrimaryEndpointForTokenAuth(String endpoint) {
String[] parts = endpoint.split("\\.");
parts[0] = parts[0].endsWith("-secondary") ? parts[0].substring(0, parts[0].length() - "-secondary".length())
: parts[0];
return String.join(".", parts);
}
/**
* Gets the default http log option for Storage Blob.
*
* @return the default http log options.
*/
public static HttpLogOptions getDefaultHttpLogOptions() {
HttpLogOptions defaultOptions = new HttpLogOptions();
BlobHeadersAndQueryParameters.getBlobHeaders().forEach(defaultOptions::addAllowedHeaderName);
BlobHeadersAndQueryParameters.getBlobQueryParameters().forEach(defaultOptions::addAllowedQueryParamName);
return defaultOptions;
}
/**
* Gets the endpoint for the blob service based on the parsed URL.
*
* @param parts The {@link BlobUrlParts} from the parse URL.
* @return The endpoint for the blob service.
*/
public static String getEndpoint(BlobUrlParts parts) throws MalformedURLException {
if (ModelHelper.determineAuthorityIsIpStyle(parts.getHost())) {
return String.format("%s:
} else {
return String.format("%s:
}
}
/**
* Validates that the client is properly configured to use https.
*
* @param objectToCheck The object to check for.
* @param objectName The name of the object.
* @param endpoint The endpoint for the client.
*/
public static void httpsValidation(Object objectToCheck, String objectName, String endpoint, ClientLogger logger) {
if (objectToCheck != null && !BlobUrlParts.parse(endpoint).getScheme().equals(Constants.HTTPS)) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Using a(n) " + objectName + " requires https"));
}
}
/*
* Creates a {@link UserAgentPolicy} using the default blob module name and version.
*
* @param configuration Configuration store used to determine whether telemetry information should be included.
* @param logOptions Logging options to set in the logging policy.
* @return The default {@link UserAgentPolicy} for the module.
*/
/*
* Creates a {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} used to validate response data from
* the service.
*
* @return The {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} for the module.
*/
private static HttpPipelinePolicy getResponseValidationPolicy() {
return new ResponseValidationPolicyBuilder()
.addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID)
.addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256)
.build();
}
} | class BuilderHelper {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-storage-blob.properties");
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Constructs a {@link HttpPipeline} from values passed from a builder.
*
* @param storageSharedKeyCredential {@link StorageSharedKeyCredential} if present.
* @param tokenCredential {@link TokenCredential} if present.
* @param sasTokenCredential {@link SasTokenCredential} if present.
* @param endpoint The endpoint for the client.
* @param retryOptions Retry options to set in the retry policy.
* @param logOptions Logging options to set in the logging policy.
* @param httpClient HttpClient to use in the builder.
* @param additionalPolicies Additional {@link HttpPipelinePolicy policies} to set in the pipeline.
* @param configuration Configuration store contain environment settings.
* @param logger {@link ClientLogger} used to log any exception.
* @return A new {@link HttpPipeline} from the passed values.
*/
public static HttpPipeline buildPipeline(StorageSharedKeyCredential storageSharedKeyCredential,
TokenCredential tokenCredential, SasTokenCredential sasTokenCredential, String endpoint,
RequestRetryOptions retryOptions, HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, Configuration configuration, ClientLogger logger) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(getUserAgentPolicy(configuration, logOptions));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(new RequestRetryPolicy(retryOptions));
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy;
if (storageSharedKeyCredential != null) {
credentialPolicy = new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential);
} else if (tokenCredential != null) {
httpsValidation(tokenCredential, "bearer token", endpoint, logger);
credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential,
String.format("%s/.default", getPrimaryEndpointForTokenAuth(endpoint)));
} else if (sasTokenCredential != null) {
credentialPolicy = new SasTokenCredentialPolicy(sasTokenCredential);
} else {
credentialPolicy = null;
}
if (credentialPolicy != null) {
policies.add(credentialPolicy);
}
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(getResponseValidationPolicy());
policies.add(new HttpLoggingPolicy(logOptions));
policies.add(new ScrubEtagPolicy());
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
*
* @param endpoint The endpoint passed by the customer.
* @return The primary endpoint for the account. It may be the same endpoint passed if it is already a primary or it
* may have had "-secondary" stripped from the end of the account name.
*/
private static String getPrimaryEndpointForTokenAuth(String endpoint) {
String[] parts = endpoint.split("\\.");
parts[0] = parts[0].endsWith("-secondary") ? parts[0].substring(0, parts[0].length() - "-secondary".length())
: parts[0];
return String.join(".", parts);
}
/**
* Gets the default http log option for Storage Blob.
*
* @return the default http log options.
*/
public static HttpLogOptions getDefaultHttpLogOptions() {
HttpLogOptions defaultOptions = new HttpLogOptions();
BlobHeadersAndQueryParameters.getBlobHeaders().forEach(defaultOptions::addAllowedHeaderName);
BlobHeadersAndQueryParameters.getBlobQueryParameters().forEach(defaultOptions::addAllowedQueryParamName);
return defaultOptions;
}
/**
* Gets the endpoint for the blob service based on the parsed URL.
*
* @param parts The {@link BlobUrlParts} from the parse URL.
* @return The endpoint for the blob service.
*/
public static String getEndpoint(BlobUrlParts parts) throws MalformedURLException {
if (ModelHelper.determineAuthorityIsIpStyle(parts.getHost())) {
return String.format("%s:
} else {
return String.format("%s:
}
}
/**
* Validates that the client is properly configured to use https.
*
* @param objectToCheck The object to check for.
* @param objectName The name of the object.
* @param endpoint The endpoint for the client.
*/
public static void httpsValidation(Object objectToCheck, String objectName, String endpoint, ClientLogger logger) {
if (objectToCheck != null && !BlobUrlParts.parse(endpoint).getScheme().equals(Constants.HTTPS)) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Using a(n) " + objectName + " requires https"));
}
}
/*
* Creates a {@link UserAgentPolicy} using the default blob module name and version.
*
* @param configuration Configuration store used to determine whether telemetry information should be included.
* @param logOptions Logging options to set in the logging policy.
* @return The default {@link UserAgentPolicy} for the module.
*/
/*
* Creates a {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} used to validate response data from
* the service.
*
* @return The {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} for the module.
*/
private static HttpPipelinePolicy getResponseValidationPolicy() {
return new ResponseValidationPolicyBuilder()
.addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID)
.addOptionalEcho(Constants.HeaderConstants.ENCRYPTION_KEY_SHA256)
.build();
}
} |
1. Can we add one more example where user give bad date time format for example `202012-31T13:37:45Z` | private static Stream<Arguments> getSas() {
String validSas = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=1599537084"
+ "&skn=test-sas-key";
String validSasWithNoExpirationTime = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&skn=test-sas-key";
String validSasInvalidExpirationTimeFormat = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=se=2020-12-31T13:37:45Z"
+ "&skn=test-sas-key";
return Stream.of(
Arguments.of(validSas, OffsetDateTime.parse("2020-09-08T03:51:24Z")),
Arguments.of(validSasWithNoExpirationTime, OffsetDateTime.MAX),
Arguments.of(validSasInvalidExpirationTimeFormat, OffsetDateTime.MAX)
);
} | + "&se=se=2020-12-31T13:37:45Z" | private static Stream<Arguments> getSas() {
String validSas = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=1599537084"
+ "&skn=test-sas-key";
String validSasWithNoExpirationTime = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&skn=test-sas-key";
String validSasInvalidExpirationTimeFormat = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=se=2020-12-31T13:37:45Z"
+ "&skn=test-sas-key";
return Stream.of(
Arguments.of(validSas, OffsetDateTime.parse("2020-09-08T03:51:24Z")),
Arguments.of(validSasWithNoExpirationTime, OffsetDateTime.MAX),
Arguments.of(validSasInvalidExpirationTimeFormat, OffsetDateTime.MAX)
);
} | class ServiceBusSharedKeyCredentialTest {
@ParameterizedTest
@MethodSource("getSas")
public void testSharedAccessSignatureCredential(String sas, OffsetDateTime expectedExpirationTime) {
ServiceBusSharedKeyCredential serviceBusSharedKeyCredential = new ServiceBusSharedKeyCredential(sas);
StepVerifier.create(serviceBusSharedKeyCredential.getToken(new TokenRequestContext().addScopes("sb:
+ "-entity.servicebus.windows.net/.default")))
.assertNext(token -> {
assertNotNull(token.getToken());
assertEquals(sas, token.getToken());
assertEquals(expectedExpirationTime, token.getExpiresAt());
})
.verifyComplete();
}
} | class ServiceBusSharedKeyCredentialTest {
@ParameterizedTest
@MethodSource("getSas")
public void testSharedAccessSignatureCredential(String sas, OffsetDateTime expectedExpirationTime) {
ServiceBusSharedKeyCredential serviceBusSharedKeyCredential = new ServiceBusSharedKeyCredential(sas);
StepVerifier.create(serviceBusSharedKeyCredential.getToken(new TokenRequestContext().addScopes("sb:
+ "-entity.servicebus.windows.net/.default")))
.assertNext(token -> {
assertNotNull(token.getToken());
assertEquals(sas, token.getToken());
assertEquals(expectedExpirationTime, token.getExpiresAt());
})
.verifyComplete();
}
} |
What if user give a space, will it be valid for example `& se =1599537084` ? | private static Stream<Arguments> getSas() {
String validSas = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=1599537084"
+ "&skn=test-sas-key";
String validSasWithNoExpirationTime = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&skn=test-sas-key";
String validSasInvalidExpirationTimeFormat = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=se=2020-12-31T13:37:45Z"
+ "&skn=test-sas-key";
return Stream.of(
Arguments.of(validSas, OffsetDateTime.parse("2020-09-08T03:51:24Z")),
Arguments.of(validSasWithNoExpirationTime, OffsetDateTime.MAX),
Arguments.of(validSasInvalidExpirationTimeFormat, OffsetDateTime.MAX)
);
} | + "&se=1599537084" | private static Stream<Arguments> getSas() {
String validSas = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=1599537084"
+ "&skn=test-sas-key";
String validSasWithNoExpirationTime = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&skn=test-sas-key";
String validSasInvalidExpirationTimeFormat = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=se=2020-12-31T13:37:45Z"
+ "&skn=test-sas-key";
return Stream.of(
Arguments.of(validSas, OffsetDateTime.parse("2020-09-08T03:51:24Z")),
Arguments.of(validSasWithNoExpirationTime, OffsetDateTime.MAX),
Arguments.of(validSasInvalidExpirationTimeFormat, OffsetDateTime.MAX)
);
} | class ServiceBusSharedKeyCredentialTest {
@ParameterizedTest
@MethodSource("getSas")
public void testSharedAccessSignatureCredential(String sas, OffsetDateTime expectedExpirationTime) {
ServiceBusSharedKeyCredential serviceBusSharedKeyCredential = new ServiceBusSharedKeyCredential(sas);
StepVerifier.create(serviceBusSharedKeyCredential.getToken(new TokenRequestContext().addScopes("sb:
+ "-entity.servicebus.windows.net/.default")))
.assertNext(token -> {
assertNotNull(token.getToken());
assertEquals(sas, token.getToken());
assertEquals(expectedExpirationTime, token.getExpiresAt());
})
.verifyComplete();
}
} | class ServiceBusSharedKeyCredentialTest {
@ParameterizedTest
@MethodSource("getSas")
public void testSharedAccessSignatureCredential(String sas, OffsetDateTime expectedExpirationTime) {
ServiceBusSharedKeyCredential serviceBusSharedKeyCredential = new ServiceBusSharedKeyCredential(sas);
StepVerifier.create(serviceBusSharedKeyCredential.getToken(new TokenRequestContext().addScopes("sb:
+ "-entity.servicebus.windows.net/.default")))
.assertNext(token -> {
assertNotNull(token.getToken());
assertEquals(sas, token.getToken());
assertEquals(expectedExpirationTime, token.getExpiresAt());
})
.verifyComplete();
}
} |
Should we log here in case of `logger.verbose("Could not parse .... ")` to give user information that something might be wrong in their string and they have a chance to fix the formatting issue in their string? But at same time, we do not want to fill logs. | private OffsetDateTime getExpirationTime(String sharedAccessSignature) {
String[] parts = sharedAccessSignature.split("&");
return Arrays.stream(parts)
.map(part -> part.split("="))
.filter(pair -> pair.length == 2 && pair[0].equalsIgnoreCase("se"))
.findFirst()
.map(pair -> pair[1])
.map(expirationTimeStr -> {
try {
long epochSeconds = Long.parseLong(expirationTimeStr);
return Instant.ofEpochSecond(epochSeconds).atOffset(ZoneOffset.UTC);
} catch (NumberFormatException exception) {
return OffsetDateTime.MAX;
}
})
.orElse(OffsetDateTime.MAX);
} | return OffsetDateTime.MAX; | private OffsetDateTime getExpirationTime(String sharedAccessSignature) {
String[] parts = sharedAccessSignature.split("&");
return Arrays.stream(parts)
.map(part -> part.split("="))
.filter(pair -> pair.length == 2 && pair[0].equalsIgnoreCase("se"))
.findFirst()
.map(pair -> pair[1])
.map(expirationTimeStr -> {
try {
long epochSeconds = Long.parseLong(expirationTimeStr);
return Instant.ofEpochSecond(epochSeconds).atOffset(ZoneOffset.UTC);
} catch (NumberFormatException exception) {
logger.verbose("Invalid expiration time format in the SAS token: {}. Falling back to max "
+ "expiration time.", expirationTimeStr);
return OffsetDateTime.MAX;
}
})
.orElse(OffsetDateTime.MAX);
} | class ServiceBusSharedKeyCredential implements TokenCredential {
private static final String SHARED_ACCESS_SIGNATURE_FORMAT = "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s";
private static final String HASH_ALGORITHM = "HMACSHA256";
private final ClientLogger logger = new ClientLogger(ServiceBusSharedKeyCredential.class);
private final String policyName;
private final Mac hmac;
private final Duration tokenValidity;
private final String sharedAccessSignature;
/**
* Creates an instance that authorizes using the {@code policyName} and {@code sharedAccessKey}.
*
* @param policyName Name of the shared access key policy.
* @param sharedAccessKey Value of the shared access key.
* @throws IllegalArgumentException if {@code policyName}, {@code sharedAccessKey} is an empty string. If the
* {@code sharedAccessKey} is an invalid value for the hashing algorithm.
* @throws NullPointerException if {@code policyName} or {@code sharedAccessKey} is null.
* @throws UnsupportedOperationException If the hashing algorithm cannot be instantiated, which is used to generate
* the shared access signatures.
*/
public ServiceBusSharedKeyCredential(String policyName, String sharedAccessKey) {
this(policyName, sharedAccessKey, ServiceBusConstants.TOKEN_VALIDITY);
}
/**
* Creates an instance that authorizes using the {@code policyName} and {@code sharedAccessKey}. The authorization
* lasts for a period of {@code tokenValidity} before another token must be requested.
*
* @param policyName Name of the shared access key policy.
* @param sharedAccessKey Value of the shared access key.
* @param tokenValidity The duration for which the shared access signature is valid.
* @throws IllegalArgumentException if {@code policyName}, {@code sharedAccessKey} is an empty string. Or the
* duration of {@code tokenValidity} is zero or a negative value. If the {@code sharedAccessKey} is an invalid
* value for the hashing algorithm.
* @throws NullPointerException if {@code policyName}, {@code sharedAccessKey}, or {@code tokenValidity} is
* null.
* @throws UnsupportedOperationException If the hashing algorithm cannot be instantiated, which is used to generate
* the shared access signatures.
*/
public ServiceBusSharedKeyCredential(String policyName, String sharedAccessKey, Duration tokenValidity) {
Objects.requireNonNull(sharedAccessKey, "'sharedAccessKey' cannot be null.");
this.policyName = Objects.requireNonNull(policyName, "'sharedAccessKey' cannot be null.");
this.tokenValidity = Objects.requireNonNull(tokenValidity, "'tokenValidity' cannot be null.");
if (policyName.isEmpty()) {
throw new IllegalArgumentException("'policyName' cannot be an empty string.");
} else if (sharedAccessKey.isEmpty()) {
throw new IllegalArgumentException("'sharedAccessKey' cannot be an empty string.");
} else if (tokenValidity.isZero() || tokenValidity.isNegative()) {
throw new IllegalArgumentException("'tokenTimeToLive' has to positive and in the order-of seconds");
}
try {
hmac = Mac.getInstance(HASH_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
String.format("Unable to create hashing algorithm '%s'", HASH_ALGORITHM), e));
}
final byte[] sasKeyBytes = sharedAccessKey.getBytes(UTF_8);
final SecretKeySpec finalKey = new SecretKeySpec(sasKeyBytes, HASH_ALGORITHM);
try {
hmac.init(finalKey);
} catch (InvalidKeyException e) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'sharedAccessKey' is an invalid value for the hashing algorithm.", e));
}
this.sharedAccessSignature = null;
}
/**
* Creates an instance using the provided Shared Access Signature (SAS) string. The credential created using this
* constructor will not be refreshed. The expiration time is set to the time defined in "se={
* tokenValidationSeconds}`. If the SAS string does not contain this or is in invalid format, then the token
* expiration will be set to {@link OffsetDateTime
* <p><a href="https:
* programmatically.</a></p>
*
* @param sharedAccessSignature The base64 encoded shared access signature string.
* @throws NullPointerException if {@code sharedAccessSignature} is null.
*/
public ServiceBusSharedKeyCredential(String sharedAccessSignature) {
this.sharedAccessSignature = Objects.requireNonNull(sharedAccessSignature,
"'sharedAccessSignature' cannot be null");
this.policyName = null;
this.hmac = null;
this.tokenValidity = null;
}
/**
* Retrieves the token, given the audience/resources requested, for use in authorization against an Event Hubs
* namespace or a specific Event Hub instance.
*
* @param request The details of a token request
* @return A Mono that completes and returns the shared access signature.
* @throws IllegalArgumentException if {@code scopes} does not contain a single value, which is the token
* audience.
*/
@Override
public Mono<AccessToken> getToken(TokenRequestContext request) {
if (request.getScopes().size() != 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'scopes' should only contain a single argument that is the token audience or resource name."));
}
return Mono.fromCallable(() -> generateSharedAccessSignature(request.getScopes().get(0)));
}
private AccessToken generateSharedAccessSignature(final String resource) throws UnsupportedEncodingException {
if (CoreUtils.isNullOrEmpty(resource)) {
throw logger.logExceptionAsError(new IllegalArgumentException("resource cannot be empty"));
}
if (sharedAccessSignature != null) {
return new AccessToken(sharedAccessSignature, getExpirationTime(sharedAccessSignature));
}
final String utf8Encoding = UTF_8.name();
final OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plus(tokenValidity);
final String expiresOnEpochSeconds = Long.toString(expiresOn.toEpochSecond());
final String audienceUri = URLEncoder.encode(resource, utf8Encoding);
final String secretToSign = audienceUri + "\n" + expiresOnEpochSeconds;
final byte[] signatureBytes = hmac.doFinal(secretToSign.getBytes(utf8Encoding));
final String signature = Base64.getEncoder().encodeToString(signatureBytes);
final String token = String.format(Locale.US, SHARED_ACCESS_SIGNATURE_FORMAT,
audienceUri,
URLEncoder.encode(signature, utf8Encoding),
URLEncoder.encode(expiresOnEpochSeconds, utf8Encoding),
URLEncoder.encode(policyName, utf8Encoding));
return new AccessToken(token, expiresOn);
}
} | class ServiceBusSharedKeyCredential implements TokenCredential {
private static final String SHARED_ACCESS_SIGNATURE_FORMAT = "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s";
private static final String HASH_ALGORITHM = "HMACSHA256";
private final ClientLogger logger = new ClientLogger(ServiceBusSharedKeyCredential.class);
private final String policyName;
private final Mac hmac;
private final Duration tokenValidity;
private final String sharedAccessSignature;
/**
* Creates an instance that authorizes using the {@code policyName} and {@code sharedAccessKey}.
*
* @param policyName Name of the shared access key policy.
* @param sharedAccessKey Value of the shared access key.
* @throws IllegalArgumentException if {@code policyName}, {@code sharedAccessKey} is an empty string. If the
* {@code sharedAccessKey} is an invalid value for the hashing algorithm.
* @throws NullPointerException if {@code policyName} or {@code sharedAccessKey} is null.
* @throws UnsupportedOperationException If the hashing algorithm cannot be instantiated, which is used to generate
* the shared access signatures.
*/
public ServiceBusSharedKeyCredential(String policyName, String sharedAccessKey) {
this(policyName, sharedAccessKey, ServiceBusConstants.TOKEN_VALIDITY);
}
/**
* Creates an instance that authorizes using the {@code policyName} and {@code sharedAccessKey}. The authorization
* lasts for a period of {@code tokenValidity} before another token must be requested.
*
* @param policyName Name of the shared access key policy.
* @param sharedAccessKey Value of the shared access key.
* @param tokenValidity The duration for which the shared access signature is valid.
* @throws IllegalArgumentException if {@code policyName}, {@code sharedAccessKey} is an empty string. Or the
* duration of {@code tokenValidity} is zero or a negative value. If the {@code sharedAccessKey} is an invalid
* value for the hashing algorithm.
* @throws NullPointerException if {@code policyName}, {@code sharedAccessKey}, or {@code tokenValidity} is
* null.
* @throws UnsupportedOperationException If the hashing algorithm cannot be instantiated, which is used to generate
* the shared access signatures.
*/
public ServiceBusSharedKeyCredential(String policyName, String sharedAccessKey, Duration tokenValidity) {
Objects.requireNonNull(sharedAccessKey, "'sharedAccessKey' cannot be null.");
this.policyName = Objects.requireNonNull(policyName, "'sharedAccessKey' cannot be null.");
this.tokenValidity = Objects.requireNonNull(tokenValidity, "'tokenValidity' cannot be null.");
if (policyName.isEmpty()) {
throw new IllegalArgumentException("'policyName' cannot be an empty string.");
} else if (sharedAccessKey.isEmpty()) {
throw new IllegalArgumentException("'sharedAccessKey' cannot be an empty string.");
} else if (tokenValidity.isZero() || tokenValidity.isNegative()) {
throw new IllegalArgumentException("'tokenTimeToLive' has to positive and in the order-of seconds");
}
try {
hmac = Mac.getInstance(HASH_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
String.format("Unable to create hashing algorithm '%s'", HASH_ALGORITHM), e));
}
final byte[] sasKeyBytes = sharedAccessKey.getBytes(UTF_8);
final SecretKeySpec finalKey = new SecretKeySpec(sasKeyBytes, HASH_ALGORITHM);
try {
hmac.init(finalKey);
} catch (InvalidKeyException e) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'sharedAccessKey' is an invalid value for the hashing algorithm.", e));
}
this.sharedAccessSignature = null;
}
/**
* Creates an instance using the provided Shared Access Signature (SAS) string. The credential created using this
* constructor will not be refreshed. The expiration time is set to the time defined in "se={
* tokenValidationSeconds}`. If the SAS string does not contain this or is in invalid format, then the token
* expiration will be set to {@link OffsetDateTime
* <p><a href="https:
* programmatically.</a></p>
*
* @param sharedAccessSignature The base64 encoded shared access signature string.
* @throws NullPointerException if {@code sharedAccessSignature} is null.
*/
public ServiceBusSharedKeyCredential(String sharedAccessSignature) {
this.sharedAccessSignature = Objects.requireNonNull(sharedAccessSignature,
"'sharedAccessSignature' cannot be null");
this.policyName = null;
this.hmac = null;
this.tokenValidity = null;
}
/**
* Retrieves the token, given the audience/resources requested, for use in authorization against an Event Hubs
* namespace or a specific Event Hub instance.
*
* @param request The details of a token request
* @return A Mono that completes and returns the shared access signature.
* @throws IllegalArgumentException if {@code scopes} does not contain a single value, which is the token
* audience.
*/
@Override
public Mono<AccessToken> getToken(TokenRequestContext request) {
if (request.getScopes().size() != 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'scopes' should only contain a single argument that is the token audience or resource name."));
}
return Mono.fromCallable(() -> generateSharedAccessSignature(request.getScopes().get(0)));
}
private AccessToken generateSharedAccessSignature(final String resource) throws UnsupportedEncodingException {
if (CoreUtils.isNullOrEmpty(resource)) {
throw logger.logExceptionAsError(new IllegalArgumentException("resource cannot be empty"));
}
if (sharedAccessSignature != null) {
return new AccessToken(sharedAccessSignature, getExpirationTime(sharedAccessSignature));
}
final String utf8Encoding = UTF_8.name();
final OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plus(tokenValidity);
final String expiresOnEpochSeconds = Long.toString(expiresOn.toEpochSecond());
final String audienceUri = URLEncoder.encode(resource, utf8Encoding);
final String secretToSign = audienceUri + "\n" + expiresOnEpochSeconds;
final byte[] signatureBytes = hmac.doFinal(secretToSign.getBytes(utf8Encoding));
final String signature = Base64.getEncoder().encodeToString(signatureBytes);
final String token = String.format(Locale.US, SHARED_ACCESS_SIGNATURE_FORMAT,
audienceUri,
URLEncoder.encode(signature, utf8Encoding),
URLEncoder.encode(expiresOnEpochSeconds, utf8Encoding),
URLEncoder.encode(policyName, utf8Encoding));
return new AccessToken(token, expiresOn);
}
} |
We do not validate the contents of the SAS token. The service will throw an exception if there are unnecessary chars in the token. | private static Stream<Arguments> getSas() {
String validSas = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=1599537084"
+ "&skn=test-sas-key";
String validSasWithNoExpirationTime = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&skn=test-sas-key";
String validSasInvalidExpirationTimeFormat = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=se=2020-12-31T13:37:45Z"
+ "&skn=test-sas-key";
return Stream.of(
Arguments.of(validSas, OffsetDateTime.parse("2020-09-08T03:51:24Z")),
Arguments.of(validSasWithNoExpirationTime, OffsetDateTime.MAX),
Arguments.of(validSasInvalidExpirationTimeFormat, OffsetDateTime.MAX)
);
} | + "&se=1599537084" | private static Stream<Arguments> getSas() {
String validSas = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=1599537084"
+ "&skn=test-sas-key";
String validSasWithNoExpirationTime = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&skn=test-sas-key";
String validSasInvalidExpirationTimeFormat = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=se=2020-12-31T13:37:45Z"
+ "&skn=test-sas-key";
return Stream.of(
Arguments.of(validSas, OffsetDateTime.parse("2020-09-08T03:51:24Z")),
Arguments.of(validSasWithNoExpirationTime, OffsetDateTime.MAX),
Arguments.of(validSasInvalidExpirationTimeFormat, OffsetDateTime.MAX)
);
} | class ServiceBusSharedKeyCredentialTest {
@ParameterizedTest
@MethodSource("getSas")
public void testSharedAccessSignatureCredential(String sas, OffsetDateTime expectedExpirationTime) {
ServiceBusSharedKeyCredential serviceBusSharedKeyCredential = new ServiceBusSharedKeyCredential(sas);
StepVerifier.create(serviceBusSharedKeyCredential.getToken(new TokenRequestContext().addScopes("sb:
+ "-entity.servicebus.windows.net/.default")))
.assertNext(token -> {
assertNotNull(token.getToken());
assertEquals(sas, token.getToken());
assertEquals(expectedExpirationTime, token.getExpiresAt());
})
.verifyComplete();
}
} | class ServiceBusSharedKeyCredentialTest {
@ParameterizedTest
@MethodSource("getSas")
public void testSharedAccessSignatureCredential(String sas, OffsetDateTime expectedExpirationTime) {
ServiceBusSharedKeyCredential serviceBusSharedKeyCredential = new ServiceBusSharedKeyCredential(sas);
StepVerifier.create(serviceBusSharedKeyCredential.getToken(new TokenRequestContext().addScopes("sb:
+ "-entity.servicebus.windows.net/.default")))
.assertNext(token -> {
assertNotNull(token.getToken());
assertEquals(sas, token.getToken());
assertEquals(expectedExpirationTime, token.getExpiresAt());
})
.verifyComplete();
}
} |
Any non-integer format will be ignored and this test is covering that. | private static Stream<Arguments> getSas() {
String validSas = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=1599537084"
+ "&skn=test-sas-key";
String validSasWithNoExpirationTime = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&skn=test-sas-key";
String validSasInvalidExpirationTimeFormat = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=se=2020-12-31T13:37:45Z"
+ "&skn=test-sas-key";
return Stream.of(
Arguments.of(validSas, OffsetDateTime.parse("2020-09-08T03:51:24Z")),
Arguments.of(validSasWithNoExpirationTime, OffsetDateTime.MAX),
Arguments.of(validSasInvalidExpirationTimeFormat, OffsetDateTime.MAX)
);
} | + "&se=se=2020-12-31T13:37:45Z" | private static Stream<Arguments> getSas() {
String validSas = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=1599537084"
+ "&skn=test-sas-key";
String validSasWithNoExpirationTime = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&skn=test-sas-key";
String validSasInvalidExpirationTimeFormat = "SharedAccessSignature "
+ "sr=https%3A%2F%2Fentity-name.servicebus.windows.net%2F"
+ "&sig=encodedsignature%3D"
+ "&se=se=2020-12-31T13:37:45Z"
+ "&skn=test-sas-key";
return Stream.of(
Arguments.of(validSas, OffsetDateTime.parse("2020-09-08T03:51:24Z")),
Arguments.of(validSasWithNoExpirationTime, OffsetDateTime.MAX),
Arguments.of(validSasInvalidExpirationTimeFormat, OffsetDateTime.MAX)
);
} | class ServiceBusSharedKeyCredentialTest {
@ParameterizedTest
@MethodSource("getSas")
public void testSharedAccessSignatureCredential(String sas, OffsetDateTime expectedExpirationTime) {
ServiceBusSharedKeyCredential serviceBusSharedKeyCredential = new ServiceBusSharedKeyCredential(sas);
StepVerifier.create(serviceBusSharedKeyCredential.getToken(new TokenRequestContext().addScopes("sb:
+ "-entity.servicebus.windows.net/.default")))
.assertNext(token -> {
assertNotNull(token.getToken());
assertEquals(sas, token.getToken());
assertEquals(expectedExpirationTime, token.getExpiresAt());
})
.verifyComplete();
}
} | class ServiceBusSharedKeyCredentialTest {
@ParameterizedTest
@MethodSource("getSas")
public void testSharedAccessSignatureCredential(String sas, OffsetDateTime expectedExpirationTime) {
ServiceBusSharedKeyCredential serviceBusSharedKeyCredential = new ServiceBusSharedKeyCredential(sas);
StepVerifier.create(serviceBusSharedKeyCredential.getToken(new TokenRequestContext().addScopes("sb:
+ "-entity.servicebus.windows.net/.default")))
.assertNext(token -> {
assertNotNull(token.getToken());
assertEquals(sas, token.getToken());
assertEquals(expectedExpirationTime, token.getExpiresAt());
})
.verifyComplete();
}
} |
Nice! Although, I haven't observed duplicates here generally but this is a nice improvement! | public Flux<AmqpEndpointState> getEndpointStates() {
return endpointStates.distinct();
} | return endpointStates.distinct(); | public Flux<AmqpEndpointState> getEndpointStates() {
return endpointStates.distinct();
} | class ReactorReceiver implements AmqpReceiveLink {
private final AtomicBoolean hasAuthorized = new AtomicBoolean(true);
private final String entityPath;
private final Receiver receiver;
private final ReceiveLinkHandler handler;
private final TokenManager tokenManager;
private final ReactorDispatcher dispatcher;
private final Disposable subscriptions;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final EmitterProcessor<Message> messagesProcessor;
private final ClientLogger logger = new ClientLogger(ReactorReceiver.class);
private final ReplayProcessor<AmqpEndpointState> endpointStates;
private final AtomicReference<Supplier<Integer>> creditSupplier = new AtomicReference<>();
protected ReactorReceiver(String entityPath, Receiver receiver, ReceiveLinkHandler handler,
TokenManager tokenManager, ReactorDispatcher dispatcher) {
this.entityPath = entityPath;
this.receiver = receiver;
this.handler = handler;
this.tokenManager = tokenManager;
this.dispatcher = dispatcher;
this.messagesProcessor = this.handler.getDeliveredMessages()
.map(this::decodeDelivery)
.doOnNext(next -> {
if (receiver.getRemoteCredit() == 0 && !isDisposed.get()) {
final Supplier<Integer> supplier = creditSupplier.get();
if (supplier == null) {
return;
}
final Integer credits = supplier.get();
if (credits != null && credits > 0) {
addCredits(credits);
}
}
})
.subscribeWith(EmitterProcessor.create());
this.endpointStates = this.handler.getEndpointStates()
.map(state -> {
logger.verbose("connectionId[{}], path[{}], linkName[{}]: State {}", handler.getConnectionId(),
entityPath, getLinkName(), state);
return AmqpEndpointStateUtil.getConnectionState(state);
})
.subscribeWith(ReplayProcessor.cacheLastOrDefault(AmqpEndpointState.UNINITIALIZED));
this.subscriptions = this.tokenManager.getAuthorizationResults().subscribe(
response -> {
logger.verbose("Token refreshed: {}", response);
hasAuthorized.set(true);
}, error -> {
logger.info("connectionId[{}], path[{}], linkName[{}] - tokenRenewalFailure[{}]",
handler.getConnectionId(), this.entityPath, getLinkName(), error.getMessage());
hasAuthorized.set(false);
}, () -> hasAuthorized.set(false));
}
@Override
@Override
public Flux<Message> receive() {
return messagesProcessor;
}
@Override
public void addCredits(int credits) {
if (!isDisposed.get()) {
try {
dispatcher.invoke(() -> receiver.flow(credits));
} catch (IOException e) {
logger.warning("Unable to schedule work to add more credits.", e);
}
}
}
@Override
public int getCredits() {
return receiver.getRemoteCredit();
}
@Override
public void setEmptyCreditListener(Supplier<Integer> creditSupplier) {
Objects.requireNonNull(creditSupplier, "'creditSupplier' cannot be null.");
this.creditSupplier.set(creditSupplier);
}
@Override
public String getLinkName() {
return receiver.getName();
}
@Override
public String getEntityPath() {
return entityPath;
}
@Override
public String getHostname() {
return handler.getHostname();
}
@Override
public boolean isDisposed() {
return isDisposed.get();
}
@Override
public void dispose() {
if (isDisposed.getAndSet(true)) {
return;
}
subscriptions.dispose();
messagesProcessor.onComplete();
tokenManager.close();
receiver.close();
try {
dispatcher.invoke(() -> {
receiver.free();
handler.close();
});
} catch (IOException e) {
logger.warning("Could not schedule disposing of receiver on ReactorDispatcher.", e);
handler.close();
}
}
/**
* Disposes of the sender when an exception is encountered.
*
* @param condition Error condition associated with close operation.
*/
public void dispose(ErrorCondition condition) {
if (isDisposed.getAndSet(true)) {
return;
}
logger.verbose("connectionId[{}], path[{}], linkName[{}]: setting error condition {}",
handler.getConnectionId(), entityPath, getLinkName(), condition);
if (receiver.getLocalState() != EndpointState.CLOSED) {
receiver.close();
if (receiver.getCondition() == null) {
receiver.setCondition(condition);
}
}
try {
dispatcher.invoke(() -> {
receiver.free();
handler.close();
});
} catch (IOException e) {
logger.warning("Could not schedule disposing of receiver on ReactorDispatcher.", e);
handler.close();
}
messagesProcessor.onComplete();
tokenManager.close();
}
protected Message decodeDelivery(Delivery delivery) {
final int messageSize = delivery.pending();
final byte[] buffer = new byte[messageSize];
final int read = receiver.recv(buffer, 0, messageSize);
receiver.advance();
final Message message = Proton.message();
message.decode(buffer, 0, read);
delivery.settle();
return message;
}
@Override
public String toString() {
return String.format("link name: [%s], entity path: [%s]", receiver.getName(), entityPath);
}
} | class ReactorReceiver implements AmqpReceiveLink {
private final AtomicBoolean hasAuthorized = new AtomicBoolean(true);
private final String entityPath;
private final Receiver receiver;
private final ReceiveLinkHandler handler;
private final TokenManager tokenManager;
private final ReactorDispatcher dispatcher;
private final Disposable subscriptions;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final EmitterProcessor<Message> messagesProcessor;
private final ClientLogger logger = new ClientLogger(ReactorReceiver.class);
private final ReplayProcessor<AmqpEndpointState> endpointStates;
private final AtomicReference<Supplier<Integer>> creditSupplier = new AtomicReference<>();
protected ReactorReceiver(String entityPath, Receiver receiver, ReceiveLinkHandler handler,
TokenManager tokenManager, ReactorDispatcher dispatcher) {
this.entityPath = entityPath;
this.receiver = receiver;
this.handler = handler;
this.tokenManager = tokenManager;
this.dispatcher = dispatcher;
this.messagesProcessor = this.handler.getDeliveredMessages()
.map(this::decodeDelivery)
.doOnNext(next -> {
if (receiver.getRemoteCredit() == 0 && !isDisposed.get()) {
final Supplier<Integer> supplier = creditSupplier.get();
if (supplier == null) {
return;
}
final Integer credits = supplier.get();
if (credits != null && credits > 0) {
addCredits(credits);
}
}
})
.subscribeWith(EmitterProcessor.create());
this.endpointStates = this.handler.getEndpointStates()
.map(state -> {
logger.verbose("connectionId[{}], path[{}], linkName[{}]: State {}", handler.getConnectionId(),
entityPath, getLinkName(), state);
return AmqpEndpointStateUtil.getConnectionState(state);
})
.subscribeWith(ReplayProcessor.cacheLastOrDefault(AmqpEndpointState.UNINITIALIZED));
this.subscriptions = this.tokenManager.getAuthorizationResults().subscribe(
response -> {
logger.verbose("Token refreshed: {}", response);
hasAuthorized.set(true);
}, error -> {
logger.info("connectionId[{}], path[{}], linkName[{}] - tokenRenewalFailure[{}]",
handler.getConnectionId(), this.entityPath, getLinkName(), error.getMessage());
hasAuthorized.set(false);
}, () -> hasAuthorized.set(false));
}
@Override
@Override
public Flux<Message> receive() {
return messagesProcessor;
}
@Override
public void addCredits(int credits) {
if (!isDisposed.get()) {
try {
dispatcher.invoke(() -> receiver.flow(credits));
} catch (IOException e) {
logger.warning("Unable to schedule work to add more credits.", e);
}
}
}
@Override
public int getCredits() {
return receiver.getRemoteCredit();
}
@Override
public void setEmptyCreditListener(Supplier<Integer> creditSupplier) {
Objects.requireNonNull(creditSupplier, "'creditSupplier' cannot be null.");
this.creditSupplier.set(creditSupplier);
}
@Override
public String getLinkName() {
return receiver.getName();
}
@Override
public String getEntityPath() {
return entityPath;
}
@Override
public String getHostname() {
return handler.getHostname();
}
@Override
public boolean isDisposed() {
return isDisposed.get();
}
@Override
public void dispose() {
if (isDisposed.getAndSet(true)) {
return;
}
subscriptions.dispose();
messagesProcessor.onComplete();
tokenManager.close();
receiver.close();
try {
dispatcher.invoke(() -> {
receiver.free();
handler.close();
});
} catch (IOException e) {
logger.warning("Could not schedule disposing of receiver on ReactorDispatcher.", e);
handler.close();
}
}
/**
* Disposes of the sender when an exception is encountered.
*
* @param condition Error condition associated with close operation.
*/
void dispose(ErrorCondition condition) {
if (isDisposed.getAndSet(true)) {
return;
}
logger.verbose("connectionId[{}], path[{}], linkName[{}]: setting error condition {}",
handler.getConnectionId(), entityPath, getLinkName(), condition);
if (receiver.getLocalState() != EndpointState.CLOSED) {
receiver.close();
if (receiver.getCondition() == null) {
receiver.setCondition(condition);
}
}
try {
dispatcher.invoke(() -> {
receiver.free();
handler.close();
});
} catch (IOException e) {
logger.warning("Could not schedule disposing of receiver on ReactorDispatcher.", e);
handler.close();
}
messagesProcessor.onComplete();
tokenManager.close();
}
protected Message decodeDelivery(Delivery delivery) {
final int messageSize = delivery.pending();
final byte[] buffer = new byte[messageSize];
final int read = receiver.recv(buffer, 0, messageSize);
receiver.advance();
final Message message = Proton.message();
message.decode(buffer, 0, read);
delivery.settle();
return message;
}
@Override
public String toString() {
return String.format("link name: [%s], entity path: [%s]", receiver.getName(), entityPath);
}
} |
nit: "update" not "upDate" | public void componentLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String wifiComponentName = "wifiAccessPoint";
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String modelWifi = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String modelRoomWithWifi = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, wifiComponentName);
String roomWithWifiTwin = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, wifiComponentName);
List<String> modelsList = new ArrayList<>(Arrays.asList(modelWifi, modelRoomWithWifi));
try {
List<ModelData> createdList = client.createModels(modelsList);
logger.info("Created {} models successfully", createdList.size());
BasicDigitalTwin createdTwin = client.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwin,BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
assertEquals(createdTwin.getId(), roomWithWifiTwinId);
Response<String> getComponentResponse = client.getComponentWithResponse(roomWithWifiTwinId, wifiComponentName, Context.NONE);
assertEquals(getComponentResponse.getStatusCode(), HttpURLConnection.HTTP_OK);
DigitalTwinsResponse<Void> upDateComponentResponse = client.updateComponentWithResponse(
roomWithWifiTwinId,
wifiComponentName,
TestAssetsHelper.getWifiComponentUpdatePayload(),
new UpdateComponentRequestOptions(),
Context.NONE);
assertEquals(upDateComponentResponse.getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);
}
finally {
try
{
if (roomWithWifiTwinId != null)
{
client.deleteDigitalTwin(roomWithWifiTwinId);
}
if (roomWithWifiModelId != null)
{
client.deleteModel(roomWithWifiModelId);
}
if (wifiModelId != null)
{
client.deleteModel(wifiModelId);
}
}
catch (Exception ex)
{
fail("Test clean up failed: " + ex.getMessage());
}
}
} | DigitalTwinsResponse<Void> upDateComponentResponse = client.updateComponentWithResponse( | public void componentLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String wifiComponentName = "wifiAccessPoint";
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String modelWifi = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String modelRoomWithWifi = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, wifiComponentName);
String roomWithWifiTwin = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, wifiComponentName);
List<String> modelsList = new ArrayList<>(Arrays.asList(modelWifi, modelRoomWithWifi));
try {
List<ModelData> createdList = client.createModels(modelsList);
logger.info("Created {} models successfully", createdList.size());
BasicDigitalTwin createdTwin = client.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwin,BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
assertEquals(createdTwin.getId(), roomWithWifiTwinId);
Response<String> getComponentResponse = client.getComponentWithResponse(roomWithWifiTwinId, wifiComponentName, Context.NONE);
assertEquals(getComponentResponse.getStatusCode(), HttpURLConnection.HTTP_OK);
DigitalTwinsResponse<Void> updateComponentResponse = client.updateComponentWithResponse(
roomWithWifiTwinId,
wifiComponentName,
TestAssetsHelper.getWifiComponentUpdatePayload(),
new UpdateComponentRequestOptions(),
Context.NONE);
assertEquals(updateComponentResponse.getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);
}
finally {
try
{
if (roomWithWifiTwinId != null)
{
client.deleteDigitalTwin(roomWithWifiTwinId);
}
if (roomWithWifiModelId != null)
{
client.deleteModel(roomWithWifiModelId);
}
if (wifiModelId != null)
{
client.deleteModel(wifiModelId);
}
}
catch (Exception ex)
{
throw new AssertionFailedError("Test celanup failed", ex);
}
}
} | class ComponentsTests extends ComponentsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsTestBase.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class ComponentsTests extends ComponentsTestBase {
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
To preserve the full stacktrace, how about: ```java throw new AssertionFailedError("Test clean up failed", ex) ``` | public void componentLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String wifiComponentName = "wifiAccessPoint";
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String modelWifi = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String modelRoomWithWifi = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, wifiComponentName);
String roomWithWifiTwin = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, wifiComponentName);
List<String> modelsList = new ArrayList<>(Arrays.asList(modelWifi, modelRoomWithWifi));
try {
List<ModelData> createdList = client.createModels(modelsList);
logger.info("Created {} models successfully", createdList.size());
BasicDigitalTwin createdTwin = client.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwin,BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
assertEquals(createdTwin.getId(), roomWithWifiTwinId);
Response<String> getComponentResponse = client.getComponentWithResponse(roomWithWifiTwinId, wifiComponentName, Context.NONE);
assertEquals(getComponentResponse.getStatusCode(), HttpURLConnection.HTTP_OK);
DigitalTwinsResponse<Void> upDateComponentResponse = client.updateComponentWithResponse(
roomWithWifiTwinId,
wifiComponentName,
TestAssetsHelper.getWifiComponentUpdatePayload(),
new UpdateComponentRequestOptions(),
Context.NONE);
assertEquals(upDateComponentResponse.getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);
}
finally {
try
{
if (roomWithWifiTwinId != null)
{
client.deleteDigitalTwin(roomWithWifiTwinId);
}
if (roomWithWifiModelId != null)
{
client.deleteModel(roomWithWifiModelId);
}
if (wifiModelId != null)
{
client.deleteModel(wifiModelId);
}
}
catch (Exception ex)
{
fail("Test clean up failed: " + ex.getMessage());
}
}
} | fail("Test clean up failed: " + ex.getMessage()); | public void componentLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String wifiComponentName = "wifiAccessPoint";
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String modelWifi = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String modelRoomWithWifi = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, wifiComponentName);
String roomWithWifiTwin = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, wifiComponentName);
List<String> modelsList = new ArrayList<>(Arrays.asList(modelWifi, modelRoomWithWifi));
try {
List<ModelData> createdList = client.createModels(modelsList);
logger.info("Created {} models successfully", createdList.size());
BasicDigitalTwin createdTwin = client.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwin,BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
assertEquals(createdTwin.getId(), roomWithWifiTwinId);
Response<String> getComponentResponse = client.getComponentWithResponse(roomWithWifiTwinId, wifiComponentName, Context.NONE);
assertEquals(getComponentResponse.getStatusCode(), HttpURLConnection.HTTP_OK);
DigitalTwinsResponse<Void> updateComponentResponse = client.updateComponentWithResponse(
roomWithWifiTwinId,
wifiComponentName,
TestAssetsHelper.getWifiComponentUpdatePayload(),
new UpdateComponentRequestOptions(),
Context.NONE);
assertEquals(updateComponentResponse.getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);
}
finally {
try
{
if (roomWithWifiTwinId != null)
{
client.deleteDigitalTwin(roomWithWifiTwinId);
}
if (roomWithWifiModelId != null)
{
client.deleteModel(roomWithWifiModelId);
}
if (wifiModelId != null)
{
client.deleteModel(wifiModelId);
}
}
catch (Exception ex)
{
throw new AssertionFailedError("Test celanup failed", ex);
}
}
} | class ComponentsTests extends ComponentsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsTestBase.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class ComponentsTests extends ComponentsTestBase {
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
I can split it into a separate test if you feel strongly about it; I added it in here because of the convenience (the models are twins were already created). | public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsRunner(
floorModelId,
roomModelId,
hvacModelId,
modelsList -> {
List<ModelData> createdModels = client.createModels(modelsList);
logger.info("Created {} models successfully", createdModels.size());
}
);
createFloorTwinRunner(
floorTwinId,
floorModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createRoomTwinRunner(
roomTwinId,
roomModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createHvacTwinRunner(
hvacTwinId,
hvacModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true);
String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP);
String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP);
String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP);
List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false);
BasicRelationship floorRoomRelationship = client.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomPayload, BasicRelationship.class);
assertThat(floorRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Created relationship from floor -> room");
logger.info("Created {} relationship between source = {} and target = {}", floorRoomRelationship.getId(), floorRoomRelationship.getSourceId(), floorRoomRelationship.getTargetId());
BasicRelationship floorHvacRelationship = client.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorCooledByHvacPayload, BasicRelationship.class);
assertThat(floorHvacRelationship.getId())
.isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)
.as("Created relationship from floor -> hvac");
logger.info("Created {} relationship between source = {} and target = {}", floorHvacRelationship.getId(), floorHvacRelationship.getSourceId(), floorHvacRelationship.getTargetId());
BasicRelationship hvacFloorRelationship = client.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, floorTwinCoolsRelationshipPayload, BasicRelationship.class);
assertThat(hvacFloorRelationship.getId())
.isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from hvac -> floor");
logger.info("Created {} relationship between source = {} and target = {}", hvacFloorRelationship.getId(), hvacFloorRelationship.getSourceId(), hvacFloorRelationship.getTargetId());
BasicRelationship roomFloorRelationship = client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, BasicRelationship.class);
assertThat(roomFloorRelationship.getId())
.isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from room -> floor");
logger.info("Created {} relationship between source = {} and target = {}", roomFloorRelationship.getId(), roomFloorRelationship.getSourceId(), roomFloorRelationship.getTargetId());
assertRestException(
() -> client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload),
HTTP_PRECON_FAILED
);
DigitalTwinsResponse<Void> updateRelationshipResponse = client.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null, Context.NONE);
assertThat(updateRelationshipResponse.getStatusCode())
.as("Updated relationship floor -> room")
.isEqualTo(HTTP_NO_CONTENT);
logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
BasicRelationship floorContainsRoomRelationship = client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class);
assertThat(floorContainsRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Retrieved floor -> room relationship");
logger.info("Retrieved {} relationship under source {}", floorContainsRoomRelationship.getId(), floorContainsRoomRelationship.getSourceId());
List<String> incomingRelationshipsSourceIds = new ArrayList<>();
PagedIterable<IncomingRelationship> listIncomingRelationships = client.listIncomingRelationships(floorTwinId);
listIncomingRelationships.forEach(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId()));
assertThat(incomingRelationshipsSourceIds)
.as("Floor has incoming relationships from room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray()));
List<String> relationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listRelationships = client.listRelationships(floorTwinId, BasicRelationship.class);
listRelationships.forEach(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId()));
assertThat(relationshipsTargetIds)
.as("Floor has a relationship to room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray()));
List<String> containedInRelationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listContainedInRelationship = client.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, Context.NONE);
listContainedInRelationship.forEach(basicRelationship -> {
containedInRelationshipsTargetIds.add(basicRelationship.getTargetId());
logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId);
});
assertThat(containedInRelationshipsTargetIds.size())
.as("Room has only one containedIn relationship to floor")
.isEqualTo(1);
client.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId);
client.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId);
assertRestException(
() -> client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID),
HTTP_NOT_FOUND
);
} finally {
try {
logger.info("Cleaning up test resources.");
logger.info("Deleting created relationships.");
List<BasicRelationship> relationships = new ArrayList<>();
client.listRelationships(floorTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(roomTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(hvacTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
relationships.forEach(basicRelationship -> client.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()));
logger.info("Deleting created digital twins.");
client.deleteDigitalTwin(floorTwinId);
client.deleteDigitalTwin(roomTwinId);
client.deleteDigitalTwin(hvacTwinId);
logger.info("Deleting created models.");
client.deleteModel(floorModelId);
client.deleteModel(roomModelId);
client.deleteModel(hvacModelId);
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsRunner(
floorModelId,
roomModelId,
hvacModelId,
modelsList -> {
List<ModelData> createdModels = client.createModels(modelsList);
logger.info("Created {} models successfully", createdModels.size());
}
);
createFloorTwinRunner(
floorTwinId,
floorModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createRoomTwinRunner(
roomTwinId,
roomModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createHvacTwinRunner(
hvacTwinId,
hvacModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true);
String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP);
String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP);
String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP);
List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false);
BasicRelationship floorRoomRelationship = client.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomPayload, BasicRelationship.class);
assertThat(floorRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Created relationship from floor -> room");
logger.info("Created {} relationship between source = {} and target = {}", floorRoomRelationship.getId(), floorRoomRelationship.getSourceId(), floorRoomRelationship.getTargetId());
BasicRelationship floorHvacRelationship = client.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorCooledByHvacPayload, BasicRelationship.class);
assertThat(floorHvacRelationship.getId())
.isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)
.as("Created relationship from floor -> hvac");
logger.info("Created {} relationship between source = {} and target = {}", floorHvacRelationship.getId(), floorHvacRelationship.getSourceId(), floorHvacRelationship.getTargetId());
BasicRelationship hvacFloorRelationship = client.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, floorTwinCoolsRelationshipPayload, BasicRelationship.class);
assertThat(hvacFloorRelationship.getId())
.isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from hvac -> floor");
logger.info("Created {} relationship between source = {} and target = {}", hvacFloorRelationship.getId(), hvacFloorRelationship.getSourceId(), hvacFloorRelationship.getTargetId());
BasicRelationship roomFloorRelationship = client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, BasicRelationship.class);
assertThat(roomFloorRelationship.getId())
.isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from room -> floor");
logger.info("Created {} relationship between source = {} and target = {}", roomFloorRelationship.getId(), roomFloorRelationship.getSourceId(), roomFloorRelationship.getTargetId());
assertRestException(
() -> client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload),
HTTP_PRECON_FAILED
);
DigitalTwinsResponse<Void> updateRelationshipResponse = client.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null, Context.NONE);
assertThat(updateRelationshipResponse.getStatusCode())
.as("Updated relationship floor -> room")
.isEqualTo(HTTP_NO_CONTENT);
logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
BasicRelationship floorContainsRoomRelationship = client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class);
assertThat(floorContainsRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Retrieved floor -> room relationship");
logger.info("Retrieved {} relationship under source {}", floorContainsRoomRelationship.getId(), floorContainsRoomRelationship.getSourceId());
List<String> incomingRelationshipsSourceIds = new ArrayList<>();
PagedIterable<IncomingRelationship> listIncomingRelationships = client.listIncomingRelationships(floorTwinId);
listIncomingRelationships.forEach(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId()));
assertThat(incomingRelationshipsSourceIds)
.as("Floor has incoming relationships from room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray()));
List<String> relationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listRelationships = client.listRelationships(floorTwinId, BasicRelationship.class);
listRelationships.forEach(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId()));
assertThat(relationshipsTargetIds)
.as("Floor has a relationship to room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray()));
List<String> containedInRelationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listContainedInRelationship = client.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, Context.NONE);
listContainedInRelationship.forEach(basicRelationship -> {
containedInRelationshipsTargetIds.add(basicRelationship.getTargetId());
logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId);
});
assertThat(containedInRelationshipsTargetIds.size())
.as("Room has only one containedIn relationship to floor")
.isEqualTo(1);
client.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId);
client.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId);
assertRestException(
() -> client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID),
HTTP_NOT_FOUND
);
} finally {
try {
logger.info("Cleaning up test resources.");
logger.info("Deleting created relationships.");
List<BasicRelationship> relationships = new ArrayList<>();
client.listRelationships(floorTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(roomTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(hvacTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
relationships.forEach(basicRelationship -> client.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()));
logger.info("Deleting created digital twins.");
client.deleteDigitalTwin(floorTwinId);
client.deleteDigitalTwin(roomTwinId);
client.deleteDigitalTwin(hvacTwinId);
logger.info("Deleting created models.");
client.deleteModel(floorModelId);
client.deleteModel(roomModelId);
client.deleteModel(hvacModelId);
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | class DigitalTwinsRelationshipTest extends DigitalTwinsRelationshipTestBase {
private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class DigitalTwinsRelationshipTest extends DigitalTwinsRelationshipTestBase {
private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | |
Try to preserve the stacktrace here, too | public void componentLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
String wifiComponentName = "wifiAccessPoint";
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String modelWifi = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String modelRoomWithWifi = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, wifiComponentName);
String roomWithWifiTwin = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, wifiComponentName);
List<String> modelsList = new ArrayList<>(Arrays.asList(modelWifi, modelRoomWithWifi));
try {
StepVerifier
.create(asyncClient.createModels(modelsList))
.assertNext(createResponseList -> logger.info("Created {} models successfully", createResponseList.size()))
.verifyComplete();
StepVerifier.create(asyncClient.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwin, BasicDigitalTwin.class))
.assertNext(createdTwin -> {
assertEquals(createdTwin.getId(), roomWithWifiTwinId);
logger.info("Created {} twin successfully", createdTwin.getId());
})
.verifyComplete();
StepVerifier.create(asyncClient.getComponentWithResponse(roomWithWifiTwinId, wifiComponentName))
.assertNext(createResponse -> {
assertEquals(createResponse.getStatusCode(), HttpURLConnection.HTTP_OK);
logger.info("Got component successfully");
})
.verifyComplete();
StepVerifier.create(asyncClient.updateComponentWithResponse(roomWithWifiTwinId, wifiComponentName, TestAssetsHelper.getWifiComponentUpdatePayload(), new UpdateComponentRequestOptions()))
.assertNext(updateResponse -> {
assertEquals(updateResponse.getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);
logger.info("Updated component successfully");
})
.verifyComplete();
}
finally {
try
{
if (roomWithWifiTwinId != null)
{
asyncClient.deleteDigitalTwin(roomWithWifiTwinId).block();
}
if (roomWithWifiModelId != null)
{
asyncClient.deleteModel(roomWithWifiModelId).block();
}
if (wifiModelId != null)
{
asyncClient.deleteModel(wifiModelId).block();
}
}
catch (Exception ex)
{
fail("Test clean up failed: " + ex.getMessage());
}
}
} | fail("Test clean up failed: " + ex.getMessage()); | public void componentLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
String wifiComponentName = "wifiAccessPoint";
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String modelWifi = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String modelRoomWithWifi = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, wifiComponentName);
String roomWithWifiTwin = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, wifiComponentName);
List<String> modelsList = new ArrayList<>(Arrays.asList(modelWifi, modelRoomWithWifi));
try {
StepVerifier
.create(asyncClient.createModels(modelsList))
.assertNext(createResponseList -> logger.info("Created {} models successfully", createResponseList.size()))
.verifyComplete();
StepVerifier.create(asyncClient.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwin, BasicDigitalTwin.class))
.assertNext(createdTwin -> {
assertEquals(createdTwin.getId(), roomWithWifiTwinId);
logger.info("Created {} twin successfully", createdTwin.getId());
})
.verifyComplete();
StepVerifier.create(asyncClient.getComponentWithResponse(roomWithWifiTwinId, wifiComponentName))
.assertNext(createResponse -> {
assertEquals(createResponse.getStatusCode(), HttpURLConnection.HTTP_OK);
logger.info("Got component successfully");
})
.verifyComplete();
StepVerifier.create(asyncClient.updateComponentWithResponse(roomWithWifiTwinId, wifiComponentName, TestAssetsHelper.getWifiComponentUpdatePayload(), new UpdateComponentRequestOptions()))
.assertNext(updateResponse -> {
assertEquals(updateResponse.getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);
logger.info("Updated component successfully");
})
.verifyComplete();
}
finally {
try
{
if (roomWithWifiTwinId != null)
{
asyncClient.deleteDigitalTwin(roomWithWifiTwinId).block();
}
if (roomWithWifiModelId != null)
{
asyncClient.deleteModel(roomWithWifiModelId).block();
}
if (wifiModelId != null)
{
asyncClient.deleteModel(wifiModelId).block();
}
}
catch (Exception ex)
{
throw new AssertionFailedError("Test celanup failed", ex);
}
}
} | class ComponentsAsyncTests extends ComponentsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsAsyncTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class ComponentsAsyncTests extends ComponentsTestBase {
private final ClientLogger logger = new ClientLogger(ComponentsAsyncTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
:)) good catch ! | public void componentLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String wifiComponentName = "wifiAccessPoint";
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String modelWifi = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String modelRoomWithWifi = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, wifiComponentName);
String roomWithWifiTwin = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, wifiComponentName);
List<String> modelsList = new ArrayList<>(Arrays.asList(modelWifi, modelRoomWithWifi));
try {
List<ModelData> createdList = client.createModels(modelsList);
logger.info("Created {} models successfully", createdList.size());
BasicDigitalTwin createdTwin = client.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwin,BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
assertEquals(createdTwin.getId(), roomWithWifiTwinId);
Response<String> getComponentResponse = client.getComponentWithResponse(roomWithWifiTwinId, wifiComponentName, Context.NONE);
assertEquals(getComponentResponse.getStatusCode(), HttpURLConnection.HTTP_OK);
DigitalTwinsResponse<Void> upDateComponentResponse = client.updateComponentWithResponse(
roomWithWifiTwinId,
wifiComponentName,
TestAssetsHelper.getWifiComponentUpdatePayload(),
new UpdateComponentRequestOptions(),
Context.NONE);
assertEquals(upDateComponentResponse.getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);
}
finally {
try
{
if (roomWithWifiTwinId != null)
{
client.deleteDigitalTwin(roomWithWifiTwinId);
}
if (roomWithWifiModelId != null)
{
client.deleteModel(roomWithWifiModelId);
}
if (wifiModelId != null)
{
client.deleteModel(wifiModelId);
}
}
catch (Exception ex)
{
fail("Test clean up failed: " + ex.getMessage());
}
}
} | DigitalTwinsResponse<Void> upDateComponentResponse = client.updateComponentWithResponse( | public void componentLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String wifiComponentName = "wifiAccessPoint";
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String modelWifi = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String modelRoomWithWifi = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, wifiComponentName);
String roomWithWifiTwin = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, wifiComponentName);
List<String> modelsList = new ArrayList<>(Arrays.asList(modelWifi, modelRoomWithWifi));
try {
List<ModelData> createdList = client.createModels(modelsList);
logger.info("Created {} models successfully", createdList.size());
BasicDigitalTwin createdTwin = client.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwin,BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
assertEquals(createdTwin.getId(), roomWithWifiTwinId);
Response<String> getComponentResponse = client.getComponentWithResponse(roomWithWifiTwinId, wifiComponentName, Context.NONE);
assertEquals(getComponentResponse.getStatusCode(), HttpURLConnection.HTTP_OK);
DigitalTwinsResponse<Void> updateComponentResponse = client.updateComponentWithResponse(
roomWithWifiTwinId,
wifiComponentName,
TestAssetsHelper.getWifiComponentUpdatePayload(),
new UpdateComponentRequestOptions(),
Context.NONE);
assertEquals(updateComponentResponse.getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);
}
finally {
try
{
if (roomWithWifiTwinId != null)
{
client.deleteDigitalTwin(roomWithWifiTwinId);
}
if (roomWithWifiModelId != null)
{
client.deleteModel(roomWithWifiModelId);
}
if (wifiModelId != null)
{
client.deleteModel(wifiModelId);
}
}
catch (Exception ex)
{
throw new AssertionFailedError("Test celanup failed", ex);
}
}
} | class ComponentsTests extends ComponentsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsTestBase.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class ComponentsTests extends ComponentsTestBase {
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
Looks like the service caused a regression. It went from allowing api-version as header to blocking it. We are fixing it on the service side to accept header again. | public SchemaRegistryClientBuilder() {
this.policies = new ArrayList<>();
this.httpLogOptions = new HttpLogOptions();
this.maxSchemaMapSize = null;
this.typeParserMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER);
this.httpClient = null;
this.credential = null;
this.retryPolicy = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS);
HttpHeaders headers = new HttpHeaders();
headers.put("api-version", "2020-09-01-preview");
policies.add(new AddHeadersPolicy(headers));
Map<String, String> properties = CoreUtils.getProperties(CLIENT_PROPERTIES);
clientName = properties.getOrDefault(NAME, "UnknownName");
clientVersion = properties.getOrDefault(VERSION, "UnknownVersion");
} | headers.put("api-version", "2020-09-01-preview"); | public SchemaRegistryClientBuilder() {
this.policies = new ArrayList<>();
this.httpLogOptions = new HttpLogOptions();
this.maxSchemaMapSize = null;
this.typeParserMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER);
this.httpClient = null;
this.credential = null;
this.retryPolicy = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS);
HttpHeaders headers = new HttpHeaders();
headers.put("api-version", "2020-09-01-preview");
policies.add(new AddHeadersPolicy(headers));
Map<String, String> properties = CoreUtils.getProperties(CLIENT_PROPERTIES);
clientName = properties.getOrDefault(NAME, "UnknownName");
clientVersion = properties.getOrDefault(VERSION, "UnknownVersion");
} | class SchemaRegistryClientBuilder {
private final ClientLogger logger = new ClientLogger(SchemaRegistryClientBuilder.class);
private static final String DEFAULT_SCOPE = "https:
private static final String CLIENT_PROPERTIES = "azure-data-schemaregistry-client.properties";
private static final String NAME = "name";
private static final String VERSION = "version";
private static final RetryPolicy DEFAULT_RETRY_POLICY =
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS);
private final ConcurrentSkipListMap<String, Function<String, Object>> typeParserMap;
private final List<HttpPipelinePolicy> policies;
private final String clientName;
private final String clientVersion;
private String schemaRegistryUrl;
private String host;
private HttpClient httpClient;
private Integer maxSchemaMapSize;
private TokenCredential credential;
private HttpLogOptions httpLogOptions;
private HttpPipeline httpPipeline;
private RetryPolicy retryPolicy;
/**
* Constructor for CachedSchemaRegistryClientBuilder. Supplies client defaults.
*/
/**
* Sets the service endpoint for the Azure Schema Registry instance.
*
* @return The updated {@link SchemaRegistryClientBuilder} object.
* @param schemaRegistryUrl The URL of the Azure Schema Registry instance
* @throws NullPointerException if {@code schemaRegistryUrl} is null
* @throws IllegalArgumentException if {@code schemaRegistryUrl} cannot be parsed into a valid URL
*/
public SchemaRegistryClientBuilder endpoint(String schemaRegistryUrl) {
Objects.requireNonNull(schemaRegistryUrl, "'schemaRegistryUrl' cannot be null.");
try {
URL url = new URL(schemaRegistryUrl);
this.host = url.getHost();
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(
new IllegalArgumentException("'schemaRegistryUrl' must be a valid URL.", ex));
}
if (schemaRegistryUrl.endsWith("/")) {
this.schemaRegistryUrl = schemaRegistryUrl.substring(0, schemaRegistryUrl.length() - 1);
} else {
this.schemaRegistryUrl = schemaRegistryUrl;
}
return this;
}
/**
* Sets schema cache size limit. If limit is exceeded on any cache, all caches are recycled.
*
* @param maxCacheSize max size for internal schema caches in {@link SchemaRegistryAsyncClient}
* @return The updated {@link SchemaRegistryClientBuilder} object.
* @throws IllegalArgumentException on invalid maxCacheSize value
*/
public SchemaRegistryClientBuilder maxCacheSize(int maxCacheSize) {
if (maxCacheSize < SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM) {
throw logger.logExceptionAsError(new IllegalArgumentException(
String.format("Schema map size must be greater than %s entries",
SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM)));
}
this.maxSchemaMapSize = maxCacheSize;
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 SchemaRegistryClientBuilder} object.
*/
public SchemaRegistryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all other HTTP settings are ignored to build {@link SchemaRegistryAsyncClient}.
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated {@link SchemaRegistryClientBuilder} object.
*/
public SchemaRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the {@link TokenCredential} to use when authenticating HTTP requests for this
* {@link SchemaRegistryAsyncClient}.
*
* @param credential {@link TokenCredential}
* @return The updated {@link SchemaRegistryClientBuilder} object.
* @throws NullPointerException If {@code credential} is {@code null}
*/
public SchemaRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential, "'credential' cannot be null.");
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated {@link SchemaRegistryClientBuilder} object.
*/
public SchemaRegistryClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
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 SchemaRegistryAsyncClient} .
*
* @param retryPolicy user's retry policy applied to each request.
* @return The updated {@link SchemaRegistryClientBuilder} object.
*/
public SchemaRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a policy to the set of existing policies that are executed after required policies.
*
* @param policy The retry policy for service requests.
* @return The updated {@link SchemaRegistryClientBuilder} object.
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public SchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) {
policies.add(Objects.requireNonNull(policy, "'policy' cannot be null."));
return this;
}
/**
* Creates a {@link SchemaRegistryAsyncClient} based on options set in the builder.
* Every time {@code buildClient()} is called a new instance of {@link SchemaRegistryAsyncClient} is created.
*
* If {@link
* endpoint} | class SchemaRegistryClientBuilder {
private final ClientLogger logger = new ClientLogger(SchemaRegistryClientBuilder.class);
private static final String DEFAULT_SCOPE = "https:
private static final String CLIENT_PROPERTIES = "azure-data-schemaregistry-client.properties";
private static final String NAME = "name";
private static final String VERSION = "version";
private static final RetryPolicy DEFAULT_RETRY_POLICY =
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS);
private final ConcurrentSkipListMap<String, Function<String, Object>> typeParserMap;
private final List<HttpPipelinePolicy> policies;
private final String clientName;
private final String clientVersion;
private String schemaRegistryUrl;
private String host;
private HttpClient httpClient;
private Integer maxSchemaMapSize;
private TokenCredential credential;
private HttpLogOptions httpLogOptions;
private HttpPipeline httpPipeline;
private RetryPolicy retryPolicy;
/**
* Constructor for CachedSchemaRegistryClientBuilder. Supplies client defaults.
*/
/**
* Sets the service endpoint for the Azure Schema Registry instance.
*
* @return The updated {@link SchemaRegistryClientBuilder} object.
* @param schemaRegistryUrl The URL of the Azure Schema Registry instance
* @throws NullPointerException if {@code schemaRegistryUrl} is null
* @throws IllegalArgumentException if {@code schemaRegistryUrl} cannot be parsed into a valid URL
*/
public SchemaRegistryClientBuilder endpoint(String schemaRegistryUrl) {
Objects.requireNonNull(schemaRegistryUrl, "'schemaRegistryUrl' cannot be null.");
try {
URL url = new URL(schemaRegistryUrl);
this.host = url.getHost();
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(
new IllegalArgumentException("'schemaRegistryUrl' must be a valid URL.", ex));
}
if (schemaRegistryUrl.endsWith("/")) {
this.schemaRegistryUrl = schemaRegistryUrl.substring(0, schemaRegistryUrl.length() - 1);
} else {
this.schemaRegistryUrl = schemaRegistryUrl;
}
return this;
}
/**
* Sets schema cache size limit. If limit is exceeded on any cache, all caches are recycled.
*
* @param maxCacheSize max size for internal schema caches in {@link SchemaRegistryAsyncClient}
* @return The updated {@link SchemaRegistryClientBuilder} object.
* @throws IllegalArgumentException on invalid maxCacheSize value
*/
public SchemaRegistryClientBuilder maxCacheSize(int maxCacheSize) {
if (maxCacheSize < SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM) {
throw logger.logExceptionAsError(new IllegalArgumentException(
String.format("Schema map size must be greater than %s entries",
SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM)));
}
this.maxSchemaMapSize = maxCacheSize;
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 SchemaRegistryClientBuilder} object.
*/
public SchemaRegistryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all other HTTP settings are ignored to build {@link SchemaRegistryAsyncClient}.
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
* @return The updated {@link SchemaRegistryClientBuilder} object.
*/
public SchemaRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the {@link TokenCredential} to use when authenticating HTTP requests for this
* {@link SchemaRegistryAsyncClient}.
*
* @param credential {@link TokenCredential}
* @return The updated {@link SchemaRegistryClientBuilder} object.
* @throws NullPointerException If {@code credential} is {@code null}
*/
public SchemaRegistryClientBuilder credential(TokenCredential credential) {
this.credential = Objects.requireNonNull(credential, "'credential' cannot be null.");
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return The updated {@link SchemaRegistryClientBuilder} object.
*/
public SchemaRegistryClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
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 SchemaRegistryAsyncClient} .
*
* @param retryPolicy user's retry policy applied to each request.
* @return The updated {@link SchemaRegistryClientBuilder} object.
*/
public SchemaRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Adds a policy to the set of existing policies that are executed after required policies.
*
* @param policy The retry policy for service requests.
* @return The updated {@link SchemaRegistryClientBuilder} object.
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public SchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) {
policies.add(Objects.requireNonNull(policy, "'policy' cannot be null."));
return this;
}
/**
* Creates a {@link SchemaRegistryAsyncClient} based on options set in the builder.
* Every time {@code buildClient()} is called a new instance of {@link SchemaRegistryAsyncClient} is created.
*
* If {@link
* endpoint} |
is this intended? | public static void main(final String[] args) {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContentFromUrl("https:
Mono<List<FormPage>> contentPageResults = recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
contentPageResults.subscribe(formPages -> {
for (int i = 0; i < formPages.size(); i++) {
final FormPage formPage = formPages.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Has width: %f and height: %f, measured with unit: %s%n", formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
final StringBuilder boundingBoxStr = new StringBuilder();
if (formTableCell.getBoundingBox() != null) {
formTableCell.getBoundingBox().getPoints().forEach(point ->
boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY())));
}
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
boundingBoxStr);
});
System.out.println();
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | client.beginRecognizeContentFromUrl("https: | public static void main(final String[] args) {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContentFromUrl("https:
Mono<List<FormPage>> contentPageResults = recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
contentPageResults.subscribe(formPages -> {
for (int i = 0; i < formPages.size(); i++) {
final FormPage formPage = formPages.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Has width: %f and height: %f, measured with unit: %s%n", formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
final StringBuilder boundingBoxStr = new StringBuilder();
if (formTableCell.getBoundingBox() != null) {
formTableCell.getBoundingBox().getPoints().forEach(point ->
boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY())));
}
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
boundingBoxStr);
});
System.out.println();
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeContentFromUrlAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
} | class RecognizeContentFromUrlAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
} |
Could this be split out into a separate test? | public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsRunner(
floorModelId,
roomModelId,
hvacModelId,
modelsList -> {
List<ModelData> createdModels = client.createModels(modelsList);
logger.info("Created {} models successfully", createdModels.size());
}
);
createFloorTwinRunner(
floorTwinId,
floorModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createRoomTwinRunner(
roomTwinId,
roomModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createHvacTwinRunner(
hvacTwinId,
hvacModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true);
String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP);
String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP);
String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP);
List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false);
BasicRelationship floorRoomRelationship = client.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomPayload, BasicRelationship.class);
assertThat(floorRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Created relationship from floor -> room");
logger.info("Created {} relationship between source = {} and target = {}", floorRoomRelationship.getId(), floorRoomRelationship.getSourceId(), floorRoomRelationship.getTargetId());
BasicRelationship floorHvacRelationship = client.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorCooledByHvacPayload, BasicRelationship.class);
assertThat(floorHvacRelationship.getId())
.isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)
.as("Created relationship from floor -> hvac");
logger.info("Created {} relationship between source = {} and target = {}", floorHvacRelationship.getId(), floorHvacRelationship.getSourceId(), floorHvacRelationship.getTargetId());
BasicRelationship hvacFloorRelationship = client.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, floorTwinCoolsRelationshipPayload, BasicRelationship.class);
assertThat(hvacFloorRelationship.getId())
.isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from hvac -> floor");
logger.info("Created {} relationship between source = {} and target = {}", hvacFloorRelationship.getId(), hvacFloorRelationship.getSourceId(), hvacFloorRelationship.getTargetId());
BasicRelationship roomFloorRelationship = client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, BasicRelationship.class);
assertThat(roomFloorRelationship.getId())
.isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from room -> floor");
logger.info("Created {} relationship between source = {} and target = {}", roomFloorRelationship.getId(), roomFloorRelationship.getSourceId(), roomFloorRelationship.getTargetId());
assertRestException(
() -> client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload),
HTTP_PRECON_FAILED
);
DigitalTwinsResponse<Void> updateRelationshipResponse = client.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null, Context.NONE);
assertThat(updateRelationshipResponse.getStatusCode())
.as("Updated relationship floor -> room")
.isEqualTo(HTTP_NO_CONTENT);
logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
BasicRelationship floorContainsRoomRelationship = client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class);
assertThat(floorContainsRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Retrieved floor -> room relationship");
logger.info("Retrieved {} relationship under source {}", floorContainsRoomRelationship.getId(), floorContainsRoomRelationship.getSourceId());
List<String> incomingRelationshipsSourceIds = new ArrayList<>();
PagedIterable<IncomingRelationship> listIncomingRelationships = client.listIncomingRelationships(floorTwinId);
listIncomingRelationships.forEach(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId()));
assertThat(incomingRelationshipsSourceIds)
.as("Floor has incoming relationships from room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray()));
List<String> relationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listRelationships = client.listRelationships(floorTwinId, BasicRelationship.class);
listRelationships.forEach(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId()));
assertThat(relationshipsTargetIds)
.as("Floor has a relationship to room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray()));
List<String> containedInRelationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listContainedInRelationship = client.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, Context.NONE);
listContainedInRelationship.forEach(basicRelationship -> {
containedInRelationshipsTargetIds.add(basicRelationship.getTargetId());
logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId);
});
assertThat(containedInRelationshipsTargetIds.size())
.as("Room has only one containedIn relationship to floor")
.isEqualTo(1);
client.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId);
client.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId);
assertRestException(
() -> client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID),
HTTP_NOT_FOUND
);
} finally {
try {
logger.info("Cleaning up test resources.");
logger.info("Deleting created relationships.");
List<BasicRelationship> relationships = new ArrayList<>();
client.listRelationships(floorTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(roomTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(hvacTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
relationships.forEach(basicRelationship -> client.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()));
logger.info("Deleting created digital twins.");
client.deleteDigitalTwin(floorTwinId);
client.deleteDigitalTwin(roomTwinId);
client.deleteDigitalTwin(hvacTwinId);
logger.info("Deleting created models.");
client.deleteModel(floorModelId);
client.deleteModel(roomModelId);
client.deleteModel(hvacModelId);
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsRunner(
floorModelId,
roomModelId,
hvacModelId,
modelsList -> {
List<ModelData> createdModels = client.createModels(modelsList);
logger.info("Created {} models successfully", createdModels.size());
}
);
createFloorTwinRunner(
floorTwinId,
floorModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createRoomTwinRunner(
roomTwinId,
roomModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createHvacTwinRunner(
hvacTwinId,
hvacModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true);
String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP);
String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP);
String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP);
List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false);
BasicRelationship floorRoomRelationship = client.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomPayload, BasicRelationship.class);
assertThat(floorRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Created relationship from floor -> room");
logger.info("Created {} relationship between source = {} and target = {}", floorRoomRelationship.getId(), floorRoomRelationship.getSourceId(), floorRoomRelationship.getTargetId());
BasicRelationship floorHvacRelationship = client.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorCooledByHvacPayload, BasicRelationship.class);
assertThat(floorHvacRelationship.getId())
.isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)
.as("Created relationship from floor -> hvac");
logger.info("Created {} relationship between source = {} and target = {}", floorHvacRelationship.getId(), floorHvacRelationship.getSourceId(), floorHvacRelationship.getTargetId());
BasicRelationship hvacFloorRelationship = client.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, floorTwinCoolsRelationshipPayload, BasicRelationship.class);
assertThat(hvacFloorRelationship.getId())
.isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from hvac -> floor");
logger.info("Created {} relationship between source = {} and target = {}", hvacFloorRelationship.getId(), hvacFloorRelationship.getSourceId(), hvacFloorRelationship.getTargetId());
BasicRelationship roomFloorRelationship = client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, BasicRelationship.class);
assertThat(roomFloorRelationship.getId())
.isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from room -> floor");
logger.info("Created {} relationship between source = {} and target = {}", roomFloorRelationship.getId(), roomFloorRelationship.getSourceId(), roomFloorRelationship.getTargetId());
assertRestException(
() -> client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload),
HTTP_PRECON_FAILED
);
DigitalTwinsResponse<Void> updateRelationshipResponse = client.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null, Context.NONE);
assertThat(updateRelationshipResponse.getStatusCode())
.as("Updated relationship floor -> room")
.isEqualTo(HTTP_NO_CONTENT);
logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
BasicRelationship floorContainsRoomRelationship = client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class);
assertThat(floorContainsRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Retrieved floor -> room relationship");
logger.info("Retrieved {} relationship under source {}", floorContainsRoomRelationship.getId(), floorContainsRoomRelationship.getSourceId());
List<String> incomingRelationshipsSourceIds = new ArrayList<>();
PagedIterable<IncomingRelationship> listIncomingRelationships = client.listIncomingRelationships(floorTwinId);
listIncomingRelationships.forEach(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId()));
assertThat(incomingRelationshipsSourceIds)
.as("Floor has incoming relationships from room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray()));
List<String> relationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listRelationships = client.listRelationships(floorTwinId, BasicRelationship.class);
listRelationships.forEach(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId()));
assertThat(relationshipsTargetIds)
.as("Floor has a relationship to room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray()));
List<String> containedInRelationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listContainedInRelationship = client.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, Context.NONE);
listContainedInRelationship.forEach(basicRelationship -> {
containedInRelationshipsTargetIds.add(basicRelationship.getTargetId());
logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId);
});
assertThat(containedInRelationshipsTargetIds.size())
.as("Room has only one containedIn relationship to floor")
.isEqualTo(1);
client.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId);
client.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId);
assertRestException(
() -> client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID),
HTTP_NOT_FOUND
);
} finally {
try {
logger.info("Cleaning up test resources.");
logger.info("Deleting created relationships.");
List<BasicRelationship> relationships = new ArrayList<>();
client.listRelationships(floorTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(roomTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(hvacTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
relationships.forEach(basicRelationship -> client.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()));
logger.info("Deleting created digital twins.");
client.deleteDigitalTwin(floorTwinId);
client.deleteDigitalTwin(roomTwinId);
client.deleteDigitalTwin(hvacTwinId);
logger.info("Deleting created models.");
client.deleteModel(floorModelId);
client.deleteModel(roomModelId);
client.deleteModel(hvacModelId);
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | class DigitalTwinsRelationshipTest extends DigitalTwinsRelationshipTestBase {
private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class DigitalTwinsRelationshipTest extends DigitalTwinsRelationshipTestBase {
private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | |
Could this be split out into a separate test? This test is already quite long | public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsRunner(
floorModelId,
roomModelId,
hvacModelId,
modelsList -> {
List<ModelData> createdModels = client.createModels(modelsList);
logger.info("Created {} models successfully", createdModels.size());
}
);
createFloorTwinRunner(
floorTwinId,
floorModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createRoomTwinRunner(
roomTwinId,
roomModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createHvacTwinRunner(
hvacTwinId,
hvacModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true);
String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP);
String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP);
String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP);
List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false);
BasicRelationship floorRoomRelationship = client.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomPayload, BasicRelationship.class);
assertThat(floorRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Created relationship from floor -> room");
logger.info("Created {} relationship between source = {} and target = {}", floorRoomRelationship.getId(), floorRoomRelationship.getSourceId(), floorRoomRelationship.getTargetId());
BasicRelationship floorHvacRelationship = client.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorCooledByHvacPayload, BasicRelationship.class);
assertThat(floorHvacRelationship.getId())
.isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)
.as("Created relationship from floor -> hvac");
logger.info("Created {} relationship between source = {} and target = {}", floorHvacRelationship.getId(), floorHvacRelationship.getSourceId(), floorHvacRelationship.getTargetId());
BasicRelationship hvacFloorRelationship = client.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, floorTwinCoolsRelationshipPayload, BasicRelationship.class);
assertThat(hvacFloorRelationship.getId())
.isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from hvac -> floor");
logger.info("Created {} relationship between source = {} and target = {}", hvacFloorRelationship.getId(), hvacFloorRelationship.getSourceId(), hvacFloorRelationship.getTargetId());
BasicRelationship roomFloorRelationship = client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, BasicRelationship.class);
assertThat(roomFloorRelationship.getId())
.isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from room -> floor");
logger.info("Created {} relationship between source = {} and target = {}", roomFloorRelationship.getId(), roomFloorRelationship.getSourceId(), roomFloorRelationship.getTargetId());
assertRestException(
() -> client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload),
HTTP_PRECON_FAILED
);
DigitalTwinsResponse<Void> updateRelationshipResponse = client.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null, Context.NONE);
assertThat(updateRelationshipResponse.getStatusCode())
.as("Updated relationship floor -> room")
.isEqualTo(HTTP_NO_CONTENT);
logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
BasicRelationship floorContainsRoomRelationship = client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class);
assertThat(floorContainsRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Retrieved floor -> room relationship");
logger.info("Retrieved {} relationship under source {}", floorContainsRoomRelationship.getId(), floorContainsRoomRelationship.getSourceId());
List<String> incomingRelationshipsSourceIds = new ArrayList<>();
PagedIterable<IncomingRelationship> listIncomingRelationships = client.listIncomingRelationships(floorTwinId);
listIncomingRelationships.forEach(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId()));
assertThat(incomingRelationshipsSourceIds)
.as("Floor has incoming relationships from room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray()));
List<String> relationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listRelationships = client.listRelationships(floorTwinId, BasicRelationship.class);
listRelationships.forEach(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId()));
assertThat(relationshipsTargetIds)
.as("Floor has a relationship to room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray()));
List<String> containedInRelationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listContainedInRelationship = client.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, Context.NONE);
listContainedInRelationship.forEach(basicRelationship -> {
containedInRelationshipsTargetIds.add(basicRelationship.getTargetId());
logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId);
});
assertThat(containedInRelationshipsTargetIds.size())
.as("Room has only one containedIn relationship to floor")
.isEqualTo(1);
client.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId);
client.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId);
assertRestException(
() -> client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID),
HTTP_NOT_FOUND
);
} finally {
try {
logger.info("Cleaning up test resources.");
logger.info("Deleting created relationships.");
List<BasicRelationship> relationships = new ArrayList<>();
client.listRelationships(floorTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(roomTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(hvacTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
relationships.forEach(basicRelationship -> client.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()));
logger.info("Deleting created digital twins.");
client.deleteDigitalTwin(floorTwinId);
client.deleteDigitalTwin(roomTwinId);
client.deleteDigitalTwin(hvacTwinId);
logger.info("Deleting created models.");
client.deleteModel(floorModelId);
client.deleteModel(roomModelId);
client.deleteModel(hvacModelId);
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsRunner(
floorModelId,
roomModelId,
hvacModelId,
modelsList -> {
List<ModelData> createdModels = client.createModels(modelsList);
logger.info("Created {} models successfully", createdModels.size());
}
);
createFloorTwinRunner(
floorTwinId,
floorModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createRoomTwinRunner(
roomTwinId,
roomModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createHvacTwinRunner(
hvacTwinId,
hvacModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true);
String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP);
String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP);
String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP);
List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false);
BasicRelationship floorRoomRelationship = client.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomPayload, BasicRelationship.class);
assertThat(floorRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Created relationship from floor -> room");
logger.info("Created {} relationship between source = {} and target = {}", floorRoomRelationship.getId(), floorRoomRelationship.getSourceId(), floorRoomRelationship.getTargetId());
BasicRelationship floorHvacRelationship = client.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorCooledByHvacPayload, BasicRelationship.class);
assertThat(floorHvacRelationship.getId())
.isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)
.as("Created relationship from floor -> hvac");
logger.info("Created {} relationship between source = {} and target = {}", floorHvacRelationship.getId(), floorHvacRelationship.getSourceId(), floorHvacRelationship.getTargetId());
BasicRelationship hvacFloorRelationship = client.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, floorTwinCoolsRelationshipPayload, BasicRelationship.class);
assertThat(hvacFloorRelationship.getId())
.isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from hvac -> floor");
logger.info("Created {} relationship between source = {} and target = {}", hvacFloorRelationship.getId(), hvacFloorRelationship.getSourceId(), hvacFloorRelationship.getTargetId());
BasicRelationship roomFloorRelationship = client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, BasicRelationship.class);
assertThat(roomFloorRelationship.getId())
.isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from room -> floor");
logger.info("Created {} relationship between source = {} and target = {}", roomFloorRelationship.getId(), roomFloorRelationship.getSourceId(), roomFloorRelationship.getTargetId());
assertRestException(
() -> client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload),
HTTP_PRECON_FAILED
);
DigitalTwinsResponse<Void> updateRelationshipResponse = client.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null, Context.NONE);
assertThat(updateRelationshipResponse.getStatusCode())
.as("Updated relationship floor -> room")
.isEqualTo(HTTP_NO_CONTENT);
logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
BasicRelationship floorContainsRoomRelationship = client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class);
assertThat(floorContainsRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Retrieved floor -> room relationship");
logger.info("Retrieved {} relationship under source {}", floorContainsRoomRelationship.getId(), floorContainsRoomRelationship.getSourceId());
List<String> incomingRelationshipsSourceIds = new ArrayList<>();
PagedIterable<IncomingRelationship> listIncomingRelationships = client.listIncomingRelationships(floorTwinId);
listIncomingRelationships.forEach(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId()));
assertThat(incomingRelationshipsSourceIds)
.as("Floor has incoming relationships from room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray()));
List<String> relationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listRelationships = client.listRelationships(floorTwinId, BasicRelationship.class);
listRelationships.forEach(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId()));
assertThat(relationshipsTargetIds)
.as("Floor has a relationship to room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray()));
List<String> containedInRelationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listContainedInRelationship = client.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, Context.NONE);
listContainedInRelationship.forEach(basicRelationship -> {
containedInRelationshipsTargetIds.add(basicRelationship.getTargetId());
logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId);
});
assertThat(containedInRelationshipsTargetIds.size())
.as("Room has only one containedIn relationship to floor")
.isEqualTo(1);
client.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId);
client.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId);
assertRestException(
() -> client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID),
HTTP_NOT_FOUND
);
} finally {
try {
logger.info("Cleaning up test resources.");
logger.info("Deleting created relationships.");
List<BasicRelationship> relationships = new ArrayList<>();
client.listRelationships(floorTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(roomTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(hvacTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
relationships.forEach(basicRelationship -> client.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()));
logger.info("Deleting created digital twins.");
client.deleteDigitalTwin(floorTwinId);
client.deleteDigitalTwin(roomTwinId);
client.deleteDigitalTwin(hvacTwinId);
logger.info("Deleting created models.");
client.deleteModel(floorModelId);
client.deleteModel(roomModelId);
client.deleteModel(hvacModelId);
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | class DigitalTwinsRelationshipTest extends DigitalTwinsRelationshipTestBase {
private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class DigitalTwinsRelationshipTest extends DigitalTwinsRelationshipTestBase {
private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | |
I thought about that, but that would require that we create the model and twins again. Since they were already available as a part of this lifecycle test, I added this assertion in here directly. | public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsRunner(
floorModelId,
roomModelId,
hvacModelId,
modelsList -> {
List<ModelData> createdModels = client.createModels(modelsList);
logger.info("Created {} models successfully", createdModels.size());
}
);
createFloorTwinRunner(
floorTwinId,
floorModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createRoomTwinRunner(
roomTwinId,
roomModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createHvacTwinRunner(
hvacTwinId,
hvacModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true);
String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP);
String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP);
String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP);
List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false);
BasicRelationship floorRoomRelationship = client.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomPayload, BasicRelationship.class);
assertThat(floorRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Created relationship from floor -> room");
logger.info("Created {} relationship between source = {} and target = {}", floorRoomRelationship.getId(), floorRoomRelationship.getSourceId(), floorRoomRelationship.getTargetId());
BasicRelationship floorHvacRelationship = client.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorCooledByHvacPayload, BasicRelationship.class);
assertThat(floorHvacRelationship.getId())
.isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)
.as("Created relationship from floor -> hvac");
logger.info("Created {} relationship between source = {} and target = {}", floorHvacRelationship.getId(), floorHvacRelationship.getSourceId(), floorHvacRelationship.getTargetId());
BasicRelationship hvacFloorRelationship = client.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, floorTwinCoolsRelationshipPayload, BasicRelationship.class);
assertThat(hvacFloorRelationship.getId())
.isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from hvac -> floor");
logger.info("Created {} relationship between source = {} and target = {}", hvacFloorRelationship.getId(), hvacFloorRelationship.getSourceId(), hvacFloorRelationship.getTargetId());
BasicRelationship roomFloorRelationship = client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, BasicRelationship.class);
assertThat(roomFloorRelationship.getId())
.isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from room -> floor");
logger.info("Created {} relationship between source = {} and target = {}", roomFloorRelationship.getId(), roomFloorRelationship.getSourceId(), roomFloorRelationship.getTargetId());
assertRestException(
() -> client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload),
HTTP_PRECON_FAILED
);
DigitalTwinsResponse<Void> updateRelationshipResponse = client.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null, Context.NONE);
assertThat(updateRelationshipResponse.getStatusCode())
.as("Updated relationship floor -> room")
.isEqualTo(HTTP_NO_CONTENT);
logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
BasicRelationship floorContainsRoomRelationship = client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class);
assertThat(floorContainsRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Retrieved floor -> room relationship");
logger.info("Retrieved {} relationship under source {}", floorContainsRoomRelationship.getId(), floorContainsRoomRelationship.getSourceId());
List<String> incomingRelationshipsSourceIds = new ArrayList<>();
PagedIterable<IncomingRelationship> listIncomingRelationships = client.listIncomingRelationships(floorTwinId);
listIncomingRelationships.forEach(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId()));
assertThat(incomingRelationshipsSourceIds)
.as("Floor has incoming relationships from room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray()));
List<String> relationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listRelationships = client.listRelationships(floorTwinId, BasicRelationship.class);
listRelationships.forEach(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId()));
assertThat(relationshipsTargetIds)
.as("Floor has a relationship to room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray()));
List<String> containedInRelationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listContainedInRelationship = client.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, Context.NONE);
listContainedInRelationship.forEach(basicRelationship -> {
containedInRelationshipsTargetIds.add(basicRelationship.getTargetId());
logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId);
});
assertThat(containedInRelationshipsTargetIds.size())
.as("Room has only one containedIn relationship to floor")
.isEqualTo(1);
client.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId);
client.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId);
assertRestException(
() -> client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID),
HTTP_NOT_FOUND
);
} finally {
try {
logger.info("Cleaning up test resources.");
logger.info("Deleting created relationships.");
List<BasicRelationship> relationships = new ArrayList<>();
client.listRelationships(floorTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(roomTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(hvacTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
relationships.forEach(basicRelationship -> client.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()));
logger.info("Deleting created digital twins.");
client.deleteDigitalTwin(floorTwinId);
client.deleteDigitalTwin(roomTwinId);
client.deleteDigitalTwin(hvacTwinId);
logger.info("Deleting created models.");
client.deleteModel(floorModelId);
client.deleteModel(roomModelId);
client.deleteModel(hvacModelId);
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | public void relationshipLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = getUniqueModelId(FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = getUniqueModelId(ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacModelId = getUniqueModelId(HVAC_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String floorTwinId = getUniqueDigitalTwinId(FLOOR_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = getUniqueDigitalTwinId(ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
String hvacTwinId = getUniqueDigitalTwinId(HVAC_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsRunner(
floorModelId,
roomModelId,
hvacModelId,
modelsList -> {
List<ModelData> createdModels = client.createModels(modelsList);
logger.info("Created {} models successfully", createdModels.size());
}
);
createFloorTwinRunner(
floorTwinId,
floorModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createRoomTwinRunner(
roomTwinId,
roomModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
createHvacTwinRunner(
hvacTwinId,
hvacModelId,
(twinId, twin) -> {
BasicDigitalTwin createdTwin = client.createDigitalTwin(twinId, twin, BasicDigitalTwin.class);
logger.info("Created {} twin successfully", createdTwin.getId());
}
);
String floorContainsRoomPayload = getRelationshipWithPropertyPayload(roomTwinId, CONTAINS_RELATIONSHIP, "isAccessRestricted", true);
String floorTwinCoolsRelationshipPayload = getRelationshipPayload(floorTwinId, COOLS_RELATIONSHIP);
String floorTwinContainedInRelationshipPayload = getRelationshipPayload(floorTwinId, CONTAINED_IN_RELATIONSHIP);
String floorCooledByHvacPayload = getRelationshipPayload(hvacTwinId, COOLED_BY_RELATIONSHIP);
List<Object> floorContainsRoomUpdatePayload = getRelationshipUpdatePayload("/isAccessRestricted", false);
BasicRelationship floorRoomRelationship = client.createRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomPayload, BasicRelationship.class);
assertThat(floorRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Created relationship from floor -> room");
logger.info("Created {} relationship between source = {} and target = {}", floorRoomRelationship.getId(), floorRoomRelationship.getSourceId(), floorRoomRelationship.getTargetId());
BasicRelationship floorHvacRelationship = client.createRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorCooledByHvacPayload, BasicRelationship.class);
assertThat(floorHvacRelationship.getId())
.isEqualTo(FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID)
.as("Created relationship from floor -> hvac");
logger.info("Created {} relationship between source = {} and target = {}", floorHvacRelationship.getId(), floorHvacRelationship.getSourceId(), floorHvacRelationship.getTargetId());
BasicRelationship hvacFloorRelationship = client.createRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID, floorTwinCoolsRelationshipPayload, BasicRelationship.class);
assertThat(hvacFloorRelationship.getId())
.isEqualTo(HVAC_COOLS_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from hvac -> floor");
logger.info("Created {} relationship between source = {} and target = {}", hvacFloorRelationship.getId(), hvacFloorRelationship.getSourceId(), hvacFloorRelationship.getTargetId());
BasicRelationship roomFloorRelationship = client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload, BasicRelationship.class);
assertThat(roomFloorRelationship.getId())
.isEqualTo(ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID)
.as("Created relationship from room -> floor");
logger.info("Created {} relationship between source = {} and target = {}", roomFloorRelationship.getId(), roomFloorRelationship.getSourceId(), roomFloorRelationship.getTargetId());
assertRestException(
() -> client.createRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, floorTwinContainedInRelationshipPayload),
HTTP_PRECON_FAILED
);
DigitalTwinsResponse<Void> updateRelationshipResponse = client.updateRelationshipWithResponse(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorContainsRoomUpdatePayload, null, Context.NONE);
assertThat(updateRelationshipResponse.getStatusCode())
.as("Updated relationship floor -> room")
.isEqualTo(HTTP_NO_CONTENT);
logger.info("Updated {} relationship successfully in source {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
BasicRelationship floorContainsRoomRelationship = client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, BasicRelationship.class);
assertThat(floorContainsRoomRelationship.getId())
.isEqualTo(FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID)
.as("Retrieved floor -> room relationship");
logger.info("Retrieved {} relationship under source {}", floorContainsRoomRelationship.getId(), floorContainsRoomRelationship.getSourceId());
List<String> incomingRelationshipsSourceIds = new ArrayList<>();
PagedIterable<IncomingRelationship> listIncomingRelationships = client.listIncomingRelationships(floorTwinId);
listIncomingRelationships.forEach(incomingRelationship -> incomingRelationshipsSourceIds.add(incomingRelationship.getSourceId()));
assertThat(incomingRelationshipsSourceIds)
.as("Floor has incoming relationships from room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved incoming relationships for {}, found sources {}", floorTwinId, Arrays.toString(incomingRelationshipsSourceIds.toArray()));
List<String> relationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listRelationships = client.listRelationships(floorTwinId, BasicRelationship.class);
listRelationships.forEach(basicRelationship -> relationshipsTargetIds.add(basicRelationship.getTargetId()));
assertThat(relationshipsTargetIds)
.as("Floor has a relationship to room and hvac")
.containsExactlyInAnyOrder(roomTwinId, hvacTwinId);
logger.info("Retrieved all relationships for {}, found targets {}", floorTwinId, Arrays.toString(relationshipsTargetIds.toArray()));
List<String> containedInRelationshipsTargetIds = new ArrayList<>();
PagedIterable<BasicRelationship> listContainedInRelationship = client.listRelationships(roomTwinId, CONTAINED_IN_RELATIONSHIP, BasicRelationship.class, Context.NONE);
listContainedInRelationship.forEach(basicRelationship -> {
containedInRelationshipsTargetIds.add(basicRelationship.getTargetId());
logger.info("Retrieved relationship {} for twin {}", basicRelationship.getId(), roomTwinId);
});
assertThat(containedInRelationshipsTargetIds.size())
.as("Room has only one containedIn relationship to floor")
.isEqualTo(1);
client.deleteRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(roomTwinId, ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", ROOM_CONTAINED_IN_FLOOR_RELATIONSHIP_ID, roomTwinId);
client.deleteRelationship(floorTwinId, FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", FLOOR_COOLED_BY_HVAC_RELATIONSHIP_ID, floorTwinId);
client.deleteRelationship(hvacTwinId, HVAC_COOLS_FLOOR_RELATIONSHIP_ID);
logger.info("Deleted relationship {} for twin {}", HVAC_COOLS_FLOOR_RELATIONSHIP_ID, hvacTwinId);
assertRestException(
() -> client.getRelationship(floorTwinId, FLOOR_CONTAINS_ROOM_RELATIONSHIP_ID),
HTTP_NOT_FOUND
);
} finally {
try {
logger.info("Cleaning up test resources.");
logger.info("Deleting created relationships.");
List<BasicRelationship> relationships = new ArrayList<>();
client.listRelationships(floorTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(roomTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
client.listRelationships(hvacTwinId, BasicRelationship.class)
.iterableByPage()
.forEach(basicRelationshipPagedResponse -> relationships.addAll(basicRelationshipPagedResponse.getValue()));
relationships.forEach(basicRelationship -> client.deleteRelationship(basicRelationship.getSourceId(), basicRelationship.getId()));
logger.info("Deleting created digital twins.");
client.deleteDigitalTwin(floorTwinId);
client.deleteDigitalTwin(roomTwinId);
client.deleteDigitalTwin(hvacTwinId);
logger.info("Deleting created models.");
client.deleteModel(floorModelId);
client.deleteModel(roomModelId);
client.deleteModel(hvacModelId);
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | class DigitalTwinsRelationshipTest extends DigitalTwinsRelationshipTestBase {
private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class DigitalTwinsRelationshipTest extends DigitalTwinsRelationshipTestBase {
private final ClientLogger logger = new ClientLogger(DigitalTwinsRelationshipTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | |
don't we need it everywhere in this file? | public static String getUniqueModelId(String baseName, DigitalTwinsAsyncClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (modelId -> Objects.requireNonNull(client.getModel(modelId).block()).getId()), randomIntegerStringGenerator);
} | return getUniqueId(baseName, (modelId -> Objects.requireNonNull(client.getModel(modelId).block()).getId()), randomIntegerStringGenerator); | public static String getUniqueModelId(String baseName, DigitalTwinsAsyncClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (modelId -> Objects.requireNonNull(client.getModel(modelId).block()).getId()), randomIntegerStringGenerator);
} | class UniqueIdHelper {
public static String getUniqueModelId(String baseName, DigitalTwinsClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (modelId -> client.getModel(modelId).getId()), randomIntegerStringGenerator);
}
public static String getUniqueDigitalTwinId(String baseName, DigitalTwinsAsyncClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (digitalTwinId -> client.getDigitalTwin(digitalTwinId).block()), randomIntegerStringGenerator);
}
public static String getUniqueDigitalTwinId(String baseName, DigitalTwinsClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (client::getDigitalTwin), randomIntegerStringGenerator);
}
private static String getUniqueId(String baseName, Function<String, String> getResource, Function<Integer, String> randomIntegerStringGenerator) {
int maxAttempts = 10;
int maxRandomDigits = 8;
for (int attemptsMade = 0 ; attemptsMade < maxAttempts ; attemptsMade++) {
String id = baseName + randomIntegerStringGenerator.apply(maxRandomDigits);
try {
getResource.apply(id);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return id;
} else {
throw new IllegalStateException("Encountered unexpected error while searching for unique id", ex);
}
}
}
throw new IllegalStateException("Unique id could not be found with base name" + baseName);
}
} | class UniqueIdHelper {
public static String getUniqueModelId(String baseName, DigitalTwinsClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (modelId -> client.getModel(modelId).getId()), randomIntegerStringGenerator);
}
public static String getUniqueDigitalTwinId(String baseName, DigitalTwinsAsyncClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (digitalTwinId -> client.getDigitalTwin(digitalTwinId).block()), randomIntegerStringGenerator);
}
public static String getUniqueDigitalTwinId(String baseName, DigitalTwinsClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (client::getDigitalTwin), randomIntegerStringGenerator);
}
private static String getUniqueId(String baseName, Function<String, String> getResource, Function<Integer, String> randomIntegerStringGenerator) {
int maxAttempts = 10;
int maxRandomDigits = 8;
for (int attemptsMade = 0 ; attemptsMade < maxAttempts ; attemptsMade++) {
String id = baseName + randomIntegerStringGenerator.apply(maxRandomDigits);
try {
getResource.apply(id);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return id;
} else {
throw new IllegalStateException("Encountered unexpected error while searching for unique id", ex);
}
}
}
throw new IllegalStateException("Unique id could not be found with base name" + baseName);
}
} |
the required non-null check? I added it here because intellij recommended that I do; we should go through our code to see if it makes sense to add it elsewhere as well. | public static String getUniqueModelId(String baseName, DigitalTwinsAsyncClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (modelId -> Objects.requireNonNull(client.getModel(modelId).block()).getId()), randomIntegerStringGenerator);
} | return getUniqueId(baseName, (modelId -> Objects.requireNonNull(client.getModel(modelId).block()).getId()), randomIntegerStringGenerator); | public static String getUniqueModelId(String baseName, DigitalTwinsAsyncClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (modelId -> Objects.requireNonNull(client.getModel(modelId).block()).getId()), randomIntegerStringGenerator);
} | class UniqueIdHelper {
public static String getUniqueModelId(String baseName, DigitalTwinsClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (modelId -> client.getModel(modelId).getId()), randomIntegerStringGenerator);
}
public static String getUniqueDigitalTwinId(String baseName, DigitalTwinsAsyncClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (digitalTwinId -> client.getDigitalTwin(digitalTwinId).block()), randomIntegerStringGenerator);
}
public static String getUniqueDigitalTwinId(String baseName, DigitalTwinsClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (client::getDigitalTwin), randomIntegerStringGenerator);
}
private static String getUniqueId(String baseName, Function<String, String> getResource, Function<Integer, String> randomIntegerStringGenerator) {
int maxAttempts = 10;
int maxRandomDigits = 8;
for (int attemptsMade = 0 ; attemptsMade < maxAttempts ; attemptsMade++) {
String id = baseName + randomIntegerStringGenerator.apply(maxRandomDigits);
try {
getResource.apply(id);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return id;
} else {
throw new IllegalStateException("Encountered unexpected error while searching for unique id", ex);
}
}
}
throw new IllegalStateException("Unique id could not be found with base name" + baseName);
}
} | class UniqueIdHelper {
public static String getUniqueModelId(String baseName, DigitalTwinsClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (modelId -> client.getModel(modelId).getId()), randomIntegerStringGenerator);
}
public static String getUniqueDigitalTwinId(String baseName, DigitalTwinsAsyncClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (digitalTwinId -> client.getDigitalTwin(digitalTwinId).block()), randomIntegerStringGenerator);
}
public static String getUniqueDigitalTwinId(String baseName, DigitalTwinsClient client, Function<Integer, String> randomIntegerStringGenerator) {
return getUniqueId(baseName, (client::getDigitalTwin), randomIntegerStringGenerator);
}
private static String getUniqueId(String baseName, Function<String, String> getResource, Function<Integer, String> randomIntegerStringGenerator) {
int maxAttempts = 10;
int maxRandomDigits = 8;
for (int attemptsMade = 0 ; attemptsMade < maxAttempts ; attemptsMade++) {
String id = baseName + randomIntegerStringGenerator.apply(maxRandomDigits);
try {
getResource.apply(id);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return id;
} else {
throw new IllegalStateException("Encountered unexpected error while searching for unique id", ex);
}
}
}
throw new IllegalStateException("Unique id could not be found with base name" + baseName);
}
} |
why the empty spaces? if you intend to tab in , use \t ? | public static void main(String[] args) {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
ConsoleLogger.printHeader("List event routes");
ConsoleLogger.print("Listing all current event routes in your Azure Digital Twins instance");
PagedIterable<EventRoute> eventRoutes = null;
try {
eventRoutes = client.listEventRoutes();
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to list event routes");
ex.printStackTrace();
System.exit(0);
}
String existingEventRouteId = null;
for (EventRoute eventRoute : eventRoutes) {
existingEventRouteId = eventRoute.getId();
ConsoleLogger.print(String.format(" EventRouteId: %s", eventRoute.getId()));
ConsoleLogger.print(String.format(" EventRouteEndpointName: %s", eventRoute.getEndpointName()));
if (eventRoute.getFilter() != null)
{
ConsoleLogger.print(String.format(" Filter: %s", eventRoute.getFilter()));
}
ConsoleLogger.print("");
}
if (existingEventRouteId != null) {
ConsoleLogger.printHeader("Get event route");
ConsoleLogger.print(String.format("Getting a single event route with Id %s", existingEventRouteId));
try {
EventRoute existingEventRoute = client.getEventRoute(existingEventRouteId);
ConsoleLogger.print(String.format("Successfully retrieved event route with Id %s", existingEventRouteId));
ConsoleLogger.print(String.format(" EventRouteId: %s", existingEventRoute.getId()));
ConsoleLogger.print(String.format(" EventRouteEndpointName: %s", existingEventRoute.getEndpointName()));
if (existingEventRoute.getFilter() != null)
{
ConsoleLogger.print(String.format(" Filter: %s", existingEventRoute.getFilter()));
}
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to get event route with Id %s", existingEventRouteId));
ex.printStackTrace();
System.exit(0);
}
} else {
ConsoleLogger.print("No event routes exist on your Azure Digital Twins instance yet.");
}
if (parsedArguments.getEventRouteEndpointName() != null) {
ConsoleLogger.printHeader("Create an event route");
ConsoleLogger.print("An event route endpoint name was provided as an input parameter, so this sample will create a new event route");
String eventRouteId = "SomeEventRoute-" + UUID.randomUUID();
String eventRouteEndpointName = parsedArguments.getEventRouteEndpointName();
String filter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
EventRoute eventRoute = new EventRoute();
eventRoute.setEndpointName(eventRouteEndpointName);
eventRoute.setFilter(filter);
try {
ConsoleLogger.print(String.format("Creating new event route with Id %s and endpoint name %s", eventRouteId, eventRouteEndpointName));
client.createEventRoute(eventRouteId, eventRoute);
ConsoleLogger.print(String.format("Successfully created event route with Id %s", eventRouteId));
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to create new event route with Id %s", eventRouteId));
ex.printStackTrace();
System.exit(0);
}
try {
ConsoleLogger.printHeader("Delete an event route");
ConsoleLogger.print(String.format("Deleting the newly created event route with Id %s", eventRouteId));
client.deleteEventRoute(eventRouteId);
ConsoleLogger.print(String.format("Successfully created event route with Id %s", eventRouteId));
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to delete event route with Id %s", eventRouteId));
ex.printStackTrace();
System.exit(0);
}
} else {
ConsoleLogger.printWarning("No event route endpoint name was provided as an input parameter, so this sample will not create a new event route");
ConsoleLogger.printWarning("In order to create a new endpoint for this sample to use, use the Azure portal or the control plane client library.");
}
} | ConsoleLogger.print(String.format(" EventRouteId: %s", existingEventRoute.getId())); | public static void main(String[] args) {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
ConsoleLogger.printHeader("List event routes");
ConsoleLogger.print("Listing all current event routes in your Azure Digital Twins instance");
PagedIterable<EventRoute> eventRoutes = null;
try {
eventRoutes = client.listEventRoutes();
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to list event routes");
ex.printStackTrace();
System.exit(0);
}
String existingEventRouteId = null;
for (EventRoute eventRoute : eventRoutes) {
existingEventRouteId = eventRoute.getId();
ConsoleLogger.print(String.format("\tEventRouteId: %s", eventRoute.getId()));
ConsoleLogger.print(String.format("\tEventRouteEndpointName: %s", eventRoute.getEndpointName()));
if (eventRoute.getFilter() != null)
{
ConsoleLogger.print(String.format("\tFilter: %s", eventRoute.getFilter()));
}
ConsoleLogger.print("");
}
if (existingEventRouteId != null) {
ConsoleLogger.printHeader("Get event route");
ConsoleLogger.print(String.format("Getting a single event route with Id %s", existingEventRouteId));
try {
EventRoute existingEventRoute = client.getEventRoute(existingEventRouteId);
ConsoleLogger.print(String.format("Successfully retrieved event route with Id %s", existingEventRouteId));
ConsoleLogger.print(String.format("\tEventRouteId: %s", existingEventRoute.getId()));
ConsoleLogger.print(String.format("\tEventRouteEndpointName: %s", existingEventRoute.getEndpointName()));
if (existingEventRoute.getFilter() != null)
{
ConsoleLogger.print(String.format("\tFilter: %s", existingEventRoute.getFilter()));
}
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to get event route with Id %s", existingEventRouteId));
ex.printStackTrace();
System.exit(0);
}
} else {
ConsoleLogger.print("No event routes exist on your Azure Digital Twins instance yet.");
}
if (parsedArguments.getEventRouteEndpointName() != null) {
ConsoleLogger.printHeader("Create an event route");
ConsoleLogger.print("An event route endpoint name was provided as an input parameter, so this sample will create a new event route");
String eventRouteId = "SomeEventRoute-" + UUID.randomUUID();
String eventRouteEndpointName = parsedArguments.getEventRouteEndpointName();
String filter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
EventRoute eventRoute = new EventRoute();
eventRoute.setEndpointName(eventRouteEndpointName);
eventRoute.setFilter(filter);
try {
ConsoleLogger.print(String.format("Creating new event route with Id %s and endpoint name %s", eventRouteId, eventRouteEndpointName));
client.createEventRoute(eventRouteId, eventRoute);
ConsoleLogger.print(String.format("Successfully created event route with Id %s", eventRouteId));
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to create new event route with Id %s", eventRouteId));
ex.printStackTrace();
System.exit(0);
}
try {
ConsoleLogger.printHeader("Delete an event route");
ConsoleLogger.print(String.format("Deleting the newly created event route with Id %s", eventRouteId));
client.deleteEventRoute(eventRouteId);
ConsoleLogger.print(String.format("Successfully created event route with Id %s", eventRouteId));
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to delete event route with Id %s", eventRouteId));
ex.printStackTrace();
System.exit(0);
}
} else {
ConsoleLogger.printWarning("No event route endpoint name was provided as an input parameter, so this sample will not create a new event route");
ConsoleLogger.printWarning("In order to create a new endpoint for this sample to use, use the Azure portal or the control plane client library.");
}
} | class EventRoutesSyncSamples {
private static DigitalTwinsClient client;
} | class EventRoutesSyncSamples {
private static DigitalTwinsClient client;
} |
Ah, good thinking. I'll just \t instead | public static void main(String[] args) {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
ConsoleLogger.printHeader("List event routes");
ConsoleLogger.print("Listing all current event routes in your Azure Digital Twins instance");
PagedIterable<EventRoute> eventRoutes = null;
try {
eventRoutes = client.listEventRoutes();
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to list event routes");
ex.printStackTrace();
System.exit(0);
}
String existingEventRouteId = null;
for (EventRoute eventRoute : eventRoutes) {
existingEventRouteId = eventRoute.getId();
ConsoleLogger.print(String.format(" EventRouteId: %s", eventRoute.getId()));
ConsoleLogger.print(String.format(" EventRouteEndpointName: %s", eventRoute.getEndpointName()));
if (eventRoute.getFilter() != null)
{
ConsoleLogger.print(String.format(" Filter: %s", eventRoute.getFilter()));
}
ConsoleLogger.print("");
}
if (existingEventRouteId != null) {
ConsoleLogger.printHeader("Get event route");
ConsoleLogger.print(String.format("Getting a single event route with Id %s", existingEventRouteId));
try {
EventRoute existingEventRoute = client.getEventRoute(existingEventRouteId);
ConsoleLogger.print(String.format("Successfully retrieved event route with Id %s", existingEventRouteId));
ConsoleLogger.print(String.format(" EventRouteId: %s", existingEventRoute.getId()));
ConsoleLogger.print(String.format(" EventRouteEndpointName: %s", existingEventRoute.getEndpointName()));
if (existingEventRoute.getFilter() != null)
{
ConsoleLogger.print(String.format(" Filter: %s", existingEventRoute.getFilter()));
}
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to get event route with Id %s", existingEventRouteId));
ex.printStackTrace();
System.exit(0);
}
} else {
ConsoleLogger.print("No event routes exist on your Azure Digital Twins instance yet.");
}
if (parsedArguments.getEventRouteEndpointName() != null) {
ConsoleLogger.printHeader("Create an event route");
ConsoleLogger.print("An event route endpoint name was provided as an input parameter, so this sample will create a new event route");
String eventRouteId = "SomeEventRoute-" + UUID.randomUUID();
String eventRouteEndpointName = parsedArguments.getEventRouteEndpointName();
String filter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
EventRoute eventRoute = new EventRoute();
eventRoute.setEndpointName(eventRouteEndpointName);
eventRoute.setFilter(filter);
try {
ConsoleLogger.print(String.format("Creating new event route with Id %s and endpoint name %s", eventRouteId, eventRouteEndpointName));
client.createEventRoute(eventRouteId, eventRoute);
ConsoleLogger.print(String.format("Successfully created event route with Id %s", eventRouteId));
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to create new event route with Id %s", eventRouteId));
ex.printStackTrace();
System.exit(0);
}
try {
ConsoleLogger.printHeader("Delete an event route");
ConsoleLogger.print(String.format("Deleting the newly created event route with Id %s", eventRouteId));
client.deleteEventRoute(eventRouteId);
ConsoleLogger.print(String.format("Successfully created event route with Id %s", eventRouteId));
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to delete event route with Id %s", eventRouteId));
ex.printStackTrace();
System.exit(0);
}
} else {
ConsoleLogger.printWarning("No event route endpoint name was provided as an input parameter, so this sample will not create a new event route");
ConsoleLogger.printWarning("In order to create a new endpoint for this sample to use, use the Azure portal or the control plane client library.");
}
} | ConsoleLogger.print(String.format(" EventRouteId: %s", existingEventRoute.getId())); | public static void main(String[] args) {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
ConsoleLogger.printHeader("List event routes");
ConsoleLogger.print("Listing all current event routes in your Azure Digital Twins instance");
PagedIterable<EventRoute> eventRoutes = null;
try {
eventRoutes = client.listEventRoutes();
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to list event routes");
ex.printStackTrace();
System.exit(0);
}
String existingEventRouteId = null;
for (EventRoute eventRoute : eventRoutes) {
existingEventRouteId = eventRoute.getId();
ConsoleLogger.print(String.format("\tEventRouteId: %s", eventRoute.getId()));
ConsoleLogger.print(String.format("\tEventRouteEndpointName: %s", eventRoute.getEndpointName()));
if (eventRoute.getFilter() != null)
{
ConsoleLogger.print(String.format("\tFilter: %s", eventRoute.getFilter()));
}
ConsoleLogger.print("");
}
if (existingEventRouteId != null) {
ConsoleLogger.printHeader("Get event route");
ConsoleLogger.print(String.format("Getting a single event route with Id %s", existingEventRouteId));
try {
EventRoute existingEventRoute = client.getEventRoute(existingEventRouteId);
ConsoleLogger.print(String.format("Successfully retrieved event route with Id %s", existingEventRouteId));
ConsoleLogger.print(String.format("\tEventRouteId: %s", existingEventRoute.getId()));
ConsoleLogger.print(String.format("\tEventRouteEndpointName: %s", existingEventRoute.getEndpointName()));
if (existingEventRoute.getFilter() != null)
{
ConsoleLogger.print(String.format("\tFilter: %s", existingEventRoute.getFilter()));
}
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to get event route with Id %s", existingEventRouteId));
ex.printStackTrace();
System.exit(0);
}
} else {
ConsoleLogger.print("No event routes exist on your Azure Digital Twins instance yet.");
}
if (parsedArguments.getEventRouteEndpointName() != null) {
ConsoleLogger.printHeader("Create an event route");
ConsoleLogger.print("An event route endpoint name was provided as an input parameter, so this sample will create a new event route");
String eventRouteId = "SomeEventRoute-" + UUID.randomUUID();
String eventRouteEndpointName = parsedArguments.getEventRouteEndpointName();
String filter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
EventRoute eventRoute = new EventRoute();
eventRoute.setEndpointName(eventRouteEndpointName);
eventRoute.setFilter(filter);
try {
ConsoleLogger.print(String.format("Creating new event route with Id %s and endpoint name %s", eventRouteId, eventRouteEndpointName));
client.createEventRoute(eventRouteId, eventRoute);
ConsoleLogger.print(String.format("Successfully created event route with Id %s", eventRouteId));
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to create new event route with Id %s", eventRouteId));
ex.printStackTrace();
System.exit(0);
}
try {
ConsoleLogger.printHeader("Delete an event route");
ConsoleLogger.print(String.format("Deleting the newly created event route with Id %s", eventRouteId));
client.deleteEventRoute(eventRouteId);
ConsoleLogger.print(String.format("Successfully created event route with Id %s", eventRouteId));
} catch (ErrorResponseException ex) {
ConsoleLogger.printFatal(String.format("Failed to delete event route with Id %s", eventRouteId));
ex.printStackTrace();
System.exit(0);
}
} else {
ConsoleLogger.printWarning("No event route endpoint name was provided as an input parameter, so this sample will not create a new event route");
ConsoleLogger.printWarning("In order to create a new endpoint for this sample to use, use the Azure portal or the control plane client library.");
}
} | class EventRoutesSyncSamples {
private static DigitalTwinsClient client;
} | class EventRoutesSyncSamples {
private static DigitalTwinsClient client;
} |
how do you feel about using assertj's fluent assertions here? | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | assertEquals(expectedId, actual.getId()); | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} |
I'm not sure that would simplify anything in this case. Am I missing something though? | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | assertEquals(expectedId, actual.getId()); | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} |
I feel it is more readable, and adds better context to the assertion being done. | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | assertEquals(expectedId, actual.getId()); | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} |
You could also do something like: ```java assertThat(actual).extracting("id", "endpointName", "filter") .doesNotContainNull() .containsExactly(expectedId, expected.getEndpointName(), expected.getFilter()); ``` | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | assertEquals(expectedId, actual.getId()); | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} |
FYI - https://stackoverflow.com/questions/47969970/assertj-for-a-pojo-how-to-check-each-nested-property-field-in-one-chained-sente?answertab=votes#tab-top | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | assertEquals(expectedId, actual.getId()); | protected static void assertEventRoutesEqual(EventRoute expected, String expectedId, EventRoute actual) {
assertEquals(expectedId, actual.getId());
assertEquals(expected.getEndpointName(), actual.getEndpointName());
assertEquals(expected.getFilter(), actual.getFilter());
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} | class EventRoutesTestBase extends DigitalTwinsTestBase {
private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class);
static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint";
static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'";
@Test
public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@Test
public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion);
@BeforeEach
public void removeAllEventRoutes() {
DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient();
PagedIterable<EventRoute> listedEventRoutes = client.listEventRoutes();
List<String> currentEventRouteIds = new ArrayList<>();
for (EventRoute listedEventRoute : listedEventRoutes) {
currentEventRouteIds.add(listedEventRoute.getId());
}
for (String eventRouteId : currentEventRouteIds) {
logger.info("Deleting event route " + eventRouteId + " before running the next test");
client.deleteEventRoute(eventRouteId);
}
}
} |
The above uses monoError. Why is this line different? | public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} else if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
} | throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); | public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} 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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext}
* or {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred
* subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* Asynchronously renews the specified message. The lock will be renewed based on the setting specified
* on the entity. When a message is received in {@link ReceiveMode
* 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} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value.
*/
/**
* Starts the auto lock renewal for a message with the given lock.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code message} 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.
*/
public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock")));
} else if (Objects.isNull(message)) {
throw logger.logExceptionAsError(new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(),
maxLockRenewalDuration, false, ignored -> renewMessageLock(message));
renewalContainer.addOrUpdate(message.getLockToken(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot renew session lock on a non-session receiver."));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
} else if (Objects.isNull(sessionId)) {
throw logger.logExceptionAsError(new NullPointerException("'sessionId' cannot be null."));
} else if (sessionId.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sessionId' cannot be empty."));
}
final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true,
this::renewSessionLock);
renewalContainer.addOrUpdate(sessionId, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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 ReceiveMode
* 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 ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value.
*/
/**
* 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 lock renewal operation for the message.
* @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.
*/
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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} 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(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session id.
*
* @param sessionId Id for the session to renew.
* @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 IllegalArgumentException if {@code sessionId} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
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, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} |
Same question. The above uses monoError. This overload uses logger.logExceptionAsError(). | public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock")));
} else if (Objects.isNull(message)) {
throw logger.logExceptionAsError(new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(),
maxLockRenewalDuration, false, ignored -> renewMessageLock(message));
renewalContainer.addOrUpdate(message.getLockToken(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
} | throw logger.logExceptionAsError(new IllegalStateException( | 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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} 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(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext}
* or {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred
* subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* Asynchronously renews the specified message. The lock will be renewed based on the setting specified
* on the entity. When a message is received in {@link ReceiveMode
* 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} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @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 (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
}
/**
* Starts the auto lock renewal for a message with the given lock.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code message} 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.
*/
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot renew session lock on a non-session receiver."));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
} else if (Objects.isNull(sessionId)) {
throw logger.logExceptionAsError(new NullPointerException("'sessionId' cannot be null."));
} else if (sessionId.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sessionId' cannot be empty."));
}
final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true,
this::renewSessionLock);
renewalContainer.addOrUpdate(sessionId, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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 ReceiveMode
* 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 ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
}
/**
* 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 lock renewal operation for the message.
* @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.
*/
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session id.
*
* @param sessionId Id for the session to renew.
* @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 IllegalArgumentException if {@code sessionId} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
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, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} |
same question | public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot renew session lock on a non-session receiver."));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
} else if (Objects.isNull(sessionId)) {
throw logger.logExceptionAsError(new NullPointerException("'sessionId' cannot be null."));
} else if (sessionId.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sessionId' cannot be empty."));
}
final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true,
this::renewSessionLock);
renewalContainer.addOrUpdate(sessionId, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
} | throw logger.logExceptionAsError(new IllegalStateException( | public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
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, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext}
* or {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred
* subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* Asynchronously renews the specified message. The lock will be renewed based on the setting specified
* on the entity. When a message is received in {@link ReceiveMode
* 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} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @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 (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
}
/**
* Starts the auto lock renewal for a message with the given lock.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code message} 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.
*/
public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock")));
} else if (Objects.isNull(message)) {
throw logger.logExceptionAsError(new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(),
maxLockRenewalDuration, false, ignored -> renewMessageLock(message));
renewalContainer.addOrUpdate(message.getLockToken(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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 ReceiveMode
* 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 ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
}
/**
* 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 lock renewal operation for the message.
* @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.
*/
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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} 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(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session id.
*
* @param sessionId Id for the session to renew.
* @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 IllegalArgumentException if {@code sessionId} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} |
Good catch. I've replaced all instances | public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} else if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
} | throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); | public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} 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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext}
* or {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred
* subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* Asynchronously renews the specified message. The lock will be renewed based on the setting specified
* on the entity. When a message is received in {@link ReceiveMode
* 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} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value.
*/
/**
* Starts the auto lock renewal for a message with the given lock.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code message} 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.
*/
public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock")));
} else if (Objects.isNull(message)) {
throw logger.logExceptionAsError(new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(),
maxLockRenewalDuration, false, ignored -> renewMessageLock(message));
renewalContainer.addOrUpdate(message.getLockToken(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot renew session lock on a non-session receiver."));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
} else if (Objects.isNull(sessionId)) {
throw logger.logExceptionAsError(new NullPointerException("'sessionId' cannot be null."));
} else if (sessionId.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sessionId' cannot be empty."));
}
final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true,
this::renewSessionLock);
renewalContainer.addOrUpdate(sessionId, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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 ReceiveMode
* 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 ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value.
*/
/**
* 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 lock renewal operation for the message.
* @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.
*/
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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} 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(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session id.
*
* @param sessionId Id for the session to renew.
* @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 IllegalArgumentException if {@code sessionId} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
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, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} |
Although logically `lockToken` will always be there but we should check for `null` value also. | public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} else if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
return monoError(logger, new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
} | } else if (message.getLockToken().isEmpty()) { | public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} 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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext}
* or {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred
* subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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 ReceiveMode
* 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} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value.
*/
/**
* Starts the auto lock renewal for a message with the given lock.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code message} 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.
*/
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 (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
return monoError(logger, new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} 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(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
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, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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 ReceiveMode
* 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 ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value.
*/
/**
* 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 lock renewal operation for the message.
* @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.
*/
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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} 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(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session id.
*
* @param sessionId Id for the session to renew.
* @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 IllegalArgumentException if {@code sessionId} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
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, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} |
null check for message.getLockToken() | 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 (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
return monoError(logger, new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} 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(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
} | String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken()))); | 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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
} 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(), Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext}
* or {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred
* subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will
* move message into the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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 ReceiveMode
* 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} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @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 (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
} else if (message.getLockToken().isEmpty()) {
return monoError(logger, new IllegalArgumentException("'message.getLockToken()' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
}
/**
* Starts the auto lock renewal for a message with the given lock.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code message} 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.
*/
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
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, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<OffsetDateTime> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* 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 tracerProvider Tracer for telemetry.
* @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,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
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.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* 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;
}
/**
* Abandon 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 ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message) {
return abandon(message, null);
}
/**
* Abandon 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 propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token 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.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.ABANDONED, null, null,
propertiesToModify, transactionContext);
}
/**
* 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 ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message) {
return updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the
* service.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
*/
public Mono<Void> complete(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.COMPLETED, null, null,
null, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred subqueue.
*
* @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 ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message) {
return defer(message, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code message} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) {
return updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} with modified message property. This will move message into
* the deferred subqueue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
*/
public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.DEFERRED, null, null,
propertiesToModify, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter 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 ReceiveMode
* mode.
* @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 deadletter sub-queue.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param transactionContext in which this operation is taking part in. The transaction should be created first
* by {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code message}, {@code transactionContext} or {@code
* transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, ServiceBusTransactionContext transactionContext) {
return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param message The {@link ServiceBusReceivedMessage} to perform this operation.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @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 ReceiveMode
* mode.
*/
public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
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 updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(),
transactionContext);
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @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.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* 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}.
* @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.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* 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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(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}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return 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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* 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} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(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.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* 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.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* 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}.
*/
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}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return 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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return 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}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
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() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil().toInstant(),
receivedMessage.getLockedUntil()).atOffset(ZoneOffset.UTC));
}
return receivedMessage;
});
}
/**
* 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 ReceiveMode
* 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 ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @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 (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 (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken())));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(message.getLockToken(), getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(message.getLockToken(), instant,
instant.atOffset(ZoneOffset.UTC)).atOffset(ZoneOffset.UTC));
}
/**
* 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 lock renewal operation for the message.
* @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.
*/
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<OffsetDateTime> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName)
.map(instant -> instant.atOffset(ZoneOffset.UTC)));
}
/**
* Starts the auto lock renewal for a session id.
*
* @param sessionId Id for the session to renew.
* @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 IllegalArgumentException if {@code sessionId} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
public Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
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, Instant.now().plus(maxLockRenewalDuration), operation);
return operation.getCompletionOperation();
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @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.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
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 connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
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() != ReceiveMode.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))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
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.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
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 (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} |
Please install `java maven` in this file: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/spring/azure-spring-boot-test-keyvault/install_java.sh | public void keyVaultWithVirtualMachineMSI() {
final VirtualMachine vm = AZURE.virtualMachines().getByResourceGroup(SPRING_RESOURCE_GROUP, VM_NAME);
final String host = vm.getPrimaryPublicIPAddress().ipAddress();
final List<String> commands = new ArrayList<>();
commands.add(String.format("cd /home/%s", VM_USER_USERNAME));
commands.add("apt-get install maven -y");
commands.add("apt-get install git");
commands.add("mkdir azure-sdk-for-java");
commands.add("cd azure-sdk-for-java");
commands.add("git init");
commands.add("git remote add origin https:
commands.add("git config core.sparsecheckout true");
commands.add("echo sdk/spring > .git/info/sparse-checkout");
commands.add("git pull origin master");
commands.add("cd sdk/spring/");
commands.add("mvn package -Dmaven.test.skip=true");
commands.add("cd azure-spring-boot-test-application/target/");
commands.add(String.format("nohup java -jar -Xdebug "
+ "-Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n "
+ "-Dazure.keyvault.uri=%s %s &"
+ " >/log.txt 2>&1",
AZURE_KEYVAULT_URI,
"app.jar"));
vm.runCommand(new RunCommandInput().withCommandId("RunShellScript").withScript(commands));
final ResponseEntity<String> response = curlWithRetry(
String.format("http:
3,
60_000,
String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("key vault value is: {}", response.getBody());
LOGGER.info("--------------------->test virtual machine with MSI over");
} | commands.add("apt-get install git"); | public void keyVaultWithVirtualMachineMSI() {
final VirtualMachine vm = AZURE.virtualMachines().getByResourceGroup(SPRING_RESOURCE_GROUP, VM_NAME);
final String host = vm.getPrimaryPublicIPAddress().ipAddress();
final List<String> commands = new ArrayList<>();
commands.add(String.format("cd /home/%s", VM_USER_USERNAME));
commands.add("mkdir azure-sdk-for-java");
commands.add("cd azure-sdk-for-java");
commands.add("git init");
commands.add("git remote add origin https:
commands.add("git config core.sparsecheckout true");
commands.add("echo sdk/spring > .git/info/sparse-checkout");
commands.add("git pull origin master");
commands.add("cd sdk/spring/");
commands.add("mvn package -Dmaven.test.skip=true");
commands.add("cd azure-spring-boot-test-application/target/");
commands.add(String.format("nohup java -jar -Xdebug "
+ "-Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n "
+ "-Dazure.keyvault.uri=%s %s &"
+ " >/log.txt 2>&1",
AZURE_KEYVAULT_URI,
"app.jar"));
vm.runCommand(new RunCommandInput().withCommandId("RunShellScript").withScript(commands));
final ResponseEntity<String> response = curlWithRetry(
String.format("http:
3,
60_000,
String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("key vault value is: {}", response.getBody());
LOGGER.info("--------------------->test virtual machine with MSI over");
} | class KeyVaultIT {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultIT.class);
private static final String AZURE_KEYVAULT_URI = System.getenv("AZURE_KEYVAULT_URI");
private static final String KEY_VAULT_SECRET_VALUE = System.getenv("KEY_VAULT_SECRET_VALUE");
private static final String KEY_VAULT_SECRET_NAME = System.getenv("KEY_VAULT_SECRET_NAME");
private static final String SPRING_RESOURCE_GROUP = System.getenv("SPRING_RESOURCE_GROUP");
private static final String APP_SERVICE_NAME = System.getenv("APP_SERVICE_NAME");
private static final String VM_NAME = System.getenv("VM_NAME");
private static final String VM_USER_USERNAME = System.getenv("VM_USER_USERNAME");
private static final String VM_USER_PASSWORD = System.getenv("VM_USER_PASSWORD");
private static final int DEFAULT_MAX_RETRY_TIMES = 3;
private static final Azure AZURE;
private static final ClientSecretAccess CLIENT_SECRET_ACCESS;
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
static {
CLIENT_SECRET_ACCESS = ClientSecretAccess.load();
AZURE = Azure.authenticate(CLIENT_SECRET_ACCESS.credentials())
.withSubscription(CLIENT_SECRET_ACCESS.subscription());
}
@Test
public void keyVaultAsPropertySource() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
final ConfigurableApplicationContext dummy = app.start("dummy");
final ConfigurableEnvironment environment = dummy.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
for (final PropertySource<?> propertySource : propertySources) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultAsPropertySourceWithSpecificKeys() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
app.property("azure.keyvault.secret-keys", KEY_VAULT_SECRET_NAME);
LOGGER.info("====" + KEY_VAULT_SECRET_NAME );
app.start();
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultWithAppServiceMSI() {
final WebApp webApp = AZURE
.webApps()
.getByResourceGroup(SPRING_RESOURCE_GROUP, APP_SERVICE_NAME);
final MavenBasedProject app = new MavenBasedProject("../azure-spring-boot-test-application");
app.packageUp();
int retryCount = 0;
final File zipFile = new File(app.zipFile());
while (retryCount < DEFAULT_MAX_RETRY_TIMES) {
retryCount += 1;
try {
webApp.zipDeploy(zipFile);
LOGGER.info(String.format("Deployed the artifact to https:
break;
} catch (Exception e) {
LOGGER.error(String.format("Exception occurred when deploying the zip package: %s, "
+ "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES));
}
}
LOGGER.info("restarting app service...");
webApp.restart();
LOGGER.info("restarting app service finished...");
final String resourceUrl = "https:
final ResponseEntity<String> response = curlWithRetry(resourceUrl, 3, 120_000, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("--------------------->test app service with MSI over");
}
@Test
private static <T> ResponseEntity<T> curlWithRetry(String resourceUrl,
final int retryTimes,
int sleepMills,
Class<T> clazz) {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ResponseEntity<T> response = ResponseEntity.of(Optional.empty());
int rt = retryTimes;
while (rt-- > 0 && httpStatus != HttpStatus.OK) {
SdkContext.sleep(sleepMills);
LOGGER.info("CURLing " + resourceUrl);
try {
response = REST_TEMPLATE.getForEntity(resourceUrl, clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
httpStatus = response.getStatusCode();
}
return response;
}
@SpringBootApplication
public static class DumbApp {
}
} | class KeyVaultIT {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultIT.class);
private static final String AZURE_KEYVAULT_URI = System.getenv("AZURE_KEYVAULT_URI");
private static final String KEY_VAULT_SECRET_VALUE = System.getenv("KEY_VAULT_SECRET_VALUE");
private static final String KEY_VAULT_SECRET_NAME = System.getenv("KEY_VAULT_SECRET_NAME");
private static final String SPRING_RESOURCE_GROUP = System.getenv("SPRING_RESOURCE_GROUP");
private static final String APP_SERVICE_NAME = System.getenv("APP_SERVICE_NAME");
private static final String VM_NAME = System.getenv("VM_NAME");
private static final String VM_USER_USERNAME = System.getenv("VM_USER_USERNAME");
private static final String VM_USER_PASSWORD = System.getenv("VM_USER_PASSWORD");
private static final int DEFAULT_MAX_RETRY_TIMES = 3;
private static final Azure AZURE;
private static final ClientSecretAccess CLIENT_SECRET_ACCESS;
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
static {
CLIENT_SECRET_ACCESS = ClientSecretAccess.load();
AZURE = Azure.authenticate(CLIENT_SECRET_ACCESS.credentials())
.withSubscription(CLIENT_SECRET_ACCESS.subscription());
}
@Test
public void keyVaultAsPropertySource() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
final ConfigurableApplicationContext dummy = app.start("dummy");
final ConfigurableEnvironment environment = dummy.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
for (final PropertySource<?> propertySource : propertySources) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultAsPropertySourceWithSpecificKeys() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
app.property("azure.keyvault.secret-keys", KEY_VAULT_SECRET_NAME);
LOGGER.info("====" + KEY_VAULT_SECRET_NAME );
app.start();
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultWithAppServiceMSI() {
final WebApp webApp = AZURE
.webApps()
.getByResourceGroup(SPRING_RESOURCE_GROUP, APP_SERVICE_NAME);
final MavenBasedProject app = new MavenBasedProject("../azure-spring-boot-test-application");
app.packageUp();
int retryCount = 0;
final File zipFile = new File(app.zipFile());
while (retryCount < DEFAULT_MAX_RETRY_TIMES) {
retryCount += 1;
try {
webApp.zipDeploy(zipFile);
LOGGER.info(String.format("Deployed the artifact to https:
break;
} catch (Exception e) {
LOGGER.error(String.format("Exception occurred when deploying the zip package: %s, "
+ "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES));
}
}
LOGGER.info("restarting app service...");
webApp.restart();
LOGGER.info("restarting app service finished...");
final String resourceUrl = "https:
final ResponseEntity<String> response = curlWithRetry(resourceUrl, 3, 120_000, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("--------------------->test app service with MSI over");
}
@Test
private static <T> ResponseEntity<T> curlWithRetry(String resourceUrl,
final int retryTimes,
int sleepMills,
Class<T> clazz) {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ResponseEntity<T> response = ResponseEntity.of(Optional.empty());
int rt = retryTimes;
while (rt-- > 0 && httpStatus != HttpStatus.OK) {
SdkContext.sleep(sleepMills);
LOGGER.info("CURLing " + resourceUrl);
try {
response = REST_TEMPLATE.getForEntity(resourceUrl, clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
httpStatus = response.getStatusCode();
}
return response;
}
@SpringBootApplication
public static class DumbApp {
}
} |
Can we use `current` branch instead of `master` branch? Refs: https://stackoverflow.com/questions/49106104/get-current-git-branch-inside-a-java-test | public void keyVaultWithVirtualMachineMSI() {
final VirtualMachine vm = AZURE.virtualMachines().getByResourceGroup(SPRING_RESOURCE_GROUP, VM_NAME);
final String host = vm.getPrimaryPublicIPAddress().ipAddress();
final List<String> commands = new ArrayList<>();
commands.add(String.format("cd /home/%s", VM_USER_USERNAME));
commands.add("mkdir azure-sdk-for-java");
commands.add("cd azure-sdk-for-java");
commands.add("git init");
commands.add("git remote add origin https:
commands.add("git config core.sparsecheckout true");
commands.add("echo sdk/spring > .git/info/sparse-checkout");
commands.add("git pull origin master");
commands.add("cd sdk/spring/");
commands.add("mvn package -Dmaven.test.skip=true");
commands.add("cd azure-spring-boot-test-application/target/");
commands.add(String.format("nohup java -jar -Xdebug "
+ "-Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n "
+ "-Dazure.keyvault.uri=%s %s &"
+ " >/log.txt 2>&1",
AZURE_KEYVAULT_URI,
"app.jar"));
vm.runCommand(new RunCommandInput().withCommandId("RunShellScript").withScript(commands));
final ResponseEntity<String> response = curlWithRetry(
String.format("http:
3,
60_000,
String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("key vault value is: {}", response.getBody());
LOGGER.info("--------------------->test virtual machine with MSI over");
} | commands.add("git pull origin master"); | public void keyVaultWithVirtualMachineMSI() {
final VirtualMachine vm = AZURE.virtualMachines().getByResourceGroup(SPRING_RESOURCE_GROUP, VM_NAME);
final String host = vm.getPrimaryPublicIPAddress().ipAddress();
final List<String> commands = new ArrayList<>();
commands.add(String.format("cd /home/%s", VM_USER_USERNAME));
commands.add("mkdir azure-sdk-for-java");
commands.add("cd azure-sdk-for-java");
commands.add("git init");
commands.add("git remote add origin https:
commands.add("git config core.sparsecheckout true");
commands.add("echo sdk/spring > .git/info/sparse-checkout");
commands.add("git pull origin master");
commands.add("cd sdk/spring/");
commands.add("mvn package -Dmaven.test.skip=true");
commands.add("cd azure-spring-boot-test-application/target/");
commands.add(String.format("nohup java -jar -Xdebug "
+ "-Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n "
+ "-Dazure.keyvault.uri=%s %s &"
+ " >/log.txt 2>&1",
AZURE_KEYVAULT_URI,
"app.jar"));
vm.runCommand(new RunCommandInput().withCommandId("RunShellScript").withScript(commands));
final ResponseEntity<String> response = curlWithRetry(
String.format("http:
3,
60_000,
String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("key vault value is: {}", response.getBody());
LOGGER.info("--------------------->test virtual machine with MSI over");
} | class KeyVaultIT {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultIT.class);
private static final String AZURE_KEYVAULT_URI = System.getenv("AZURE_KEYVAULT_URI");
private static final String KEY_VAULT_SECRET_VALUE = System.getenv("KEY_VAULT_SECRET_VALUE");
private static final String KEY_VAULT_SECRET_NAME = System.getenv("KEY_VAULT_SECRET_NAME");
private static final String SPRING_RESOURCE_GROUP = System.getenv("SPRING_RESOURCE_GROUP");
private static final String APP_SERVICE_NAME = System.getenv("APP_SERVICE_NAME");
private static final String VM_NAME = System.getenv("VM_NAME");
private static final String VM_USER_USERNAME = System.getenv("VM_USER_USERNAME");
private static final String VM_USER_PASSWORD = System.getenv("VM_USER_PASSWORD");
private static final int DEFAULT_MAX_RETRY_TIMES = 3;
private static final Azure AZURE;
private static final ClientSecretAccess CLIENT_SECRET_ACCESS;
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
static {
CLIENT_SECRET_ACCESS = ClientSecretAccess.load();
AZURE = Azure.authenticate(CLIENT_SECRET_ACCESS.credentials())
.withSubscription(CLIENT_SECRET_ACCESS.subscription());
}
@Test
public void keyVaultAsPropertySource() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
final ConfigurableApplicationContext dummy = app.start("dummy");
final ConfigurableEnvironment environment = dummy.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
for (final PropertySource<?> propertySource : propertySources) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultAsPropertySourceWithSpecificKeys() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
app.property("azure.keyvault.secret-keys", KEY_VAULT_SECRET_NAME);
LOGGER.info("====" + KEY_VAULT_SECRET_NAME );
app.start();
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultWithAppServiceMSI() {
final WebApp webApp = AZURE
.webApps()
.getByResourceGroup(SPRING_RESOURCE_GROUP, APP_SERVICE_NAME);
final MavenBasedProject app = new MavenBasedProject("../azure-spring-boot-test-application");
app.packageUp();
int retryCount = 0;
final File zipFile = new File(app.zipFile());
while (retryCount < DEFAULT_MAX_RETRY_TIMES) {
retryCount += 1;
try {
webApp.zipDeploy(zipFile);
LOGGER.info(String.format("Deployed the artifact to https:
break;
} catch (Exception e) {
LOGGER.error(String.format("Exception occurred when deploying the zip package: %s, "
+ "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES));
}
}
LOGGER.info("restarting app service...");
webApp.restart();
LOGGER.info("restarting app service finished...");
final String resourceUrl = "https:
final ResponseEntity<String> response = curlWithRetry(resourceUrl, 3, 120_000, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("--------------------->test app service with MSI over");
}
@Test
private static <T> ResponseEntity<T> curlWithRetry(String resourceUrl,
final int retryTimes,
int sleepMills,
Class<T> clazz) {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ResponseEntity<T> response = ResponseEntity.of(Optional.empty());
int rt = retryTimes;
while (rt-- > 0 && httpStatus != HttpStatus.OK) {
SdkContext.sleep(sleepMills);
LOGGER.info("CURLing " + resourceUrl);
try {
response = REST_TEMPLATE.getForEntity(resourceUrl, clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
httpStatus = response.getStatusCode();
}
return response;
}
@SpringBootApplication
public static class DumbApp {
}
} | class KeyVaultIT {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultIT.class);
private static final String AZURE_KEYVAULT_URI = System.getenv("AZURE_KEYVAULT_URI");
private static final String KEY_VAULT_SECRET_VALUE = System.getenv("KEY_VAULT_SECRET_VALUE");
private static final String KEY_VAULT_SECRET_NAME = System.getenv("KEY_VAULT_SECRET_NAME");
private static final String SPRING_RESOURCE_GROUP = System.getenv("SPRING_RESOURCE_GROUP");
private static final String APP_SERVICE_NAME = System.getenv("APP_SERVICE_NAME");
private static final String VM_NAME = System.getenv("VM_NAME");
private static final String VM_USER_USERNAME = System.getenv("VM_USER_USERNAME");
private static final String VM_USER_PASSWORD = System.getenv("VM_USER_PASSWORD");
private static final int DEFAULT_MAX_RETRY_TIMES = 3;
private static final Azure AZURE;
private static final ClientSecretAccess CLIENT_SECRET_ACCESS;
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
static {
CLIENT_SECRET_ACCESS = ClientSecretAccess.load();
AZURE = Azure.authenticate(CLIENT_SECRET_ACCESS.credentials())
.withSubscription(CLIENT_SECRET_ACCESS.subscription());
}
@Test
public void keyVaultAsPropertySource() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
final ConfigurableApplicationContext dummy = app.start("dummy");
final ConfigurableEnvironment environment = dummy.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
for (final PropertySource<?> propertySource : propertySources) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultAsPropertySourceWithSpecificKeys() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
app.property("azure.keyvault.secret-keys", KEY_VAULT_SECRET_NAME);
LOGGER.info("====" + KEY_VAULT_SECRET_NAME );
app.start();
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultWithAppServiceMSI() {
final WebApp webApp = AZURE
.webApps()
.getByResourceGroup(SPRING_RESOURCE_GROUP, APP_SERVICE_NAME);
final MavenBasedProject app = new MavenBasedProject("../azure-spring-boot-test-application");
app.packageUp();
int retryCount = 0;
final File zipFile = new File(app.zipFile());
while (retryCount < DEFAULT_MAX_RETRY_TIMES) {
retryCount += 1;
try {
webApp.zipDeploy(zipFile);
LOGGER.info(String.format("Deployed the artifact to https:
break;
} catch (Exception e) {
LOGGER.error(String.format("Exception occurred when deploying the zip package: %s, "
+ "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES));
}
}
LOGGER.info("restarting app service...");
webApp.restart();
LOGGER.info("restarting app service finished...");
final String resourceUrl = "https:
final ResponseEntity<String> response = curlWithRetry(resourceUrl, 3, 120_000, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("--------------------->test app service with MSI over");
}
@Test
private static <T> ResponseEntity<T> curlWithRetry(String resourceUrl,
final int retryTimes,
int sleepMills,
Class<T> clazz) {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ResponseEntity<T> response = ResponseEntity.of(Optional.empty());
int rt = retryTimes;
while (rt-- > 0 && httpStatus != HttpStatus.OK) {
SdkContext.sleep(sleepMills);
LOGGER.info("CURLing " + resourceUrl);
try {
response = REST_TEMPLATE.getForEntity(resourceUrl, clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
httpStatus = response.getStatusCode();
}
return response;
}
@SpringBootApplication
public static class DumbApp {
}
} |
We need update `origin` too. Refs: https://stackoverflow.com/questions/171550/find-out-which-remote-branch-a-local-branch-is-tracking | public void keyVaultWithVirtualMachineMSI() {
final VirtualMachine vm = AZURE.virtualMachines().getByResourceGroup(SPRING_RESOURCE_GROUP, VM_NAME);
final String host = vm.getPrimaryPublicIPAddress().ipAddress();
final List<String> commands = new ArrayList<>();
commands.add(String.format("cd /home/%s", VM_USER_USERNAME));
commands.add("mkdir azure-sdk-for-java");
commands.add("cd azure-sdk-for-java");
commands.add("git init");
commands.add("git remote add origin https:
commands.add("git config core.sparsecheckout true");
commands.add("echo sdk/spring > .git/info/sparse-checkout");
commands.add("git pull origin master");
commands.add("cd sdk/spring/");
commands.add("mvn package -Dmaven.test.skip=true");
commands.add("cd azure-spring-boot-test-application/target/");
commands.add(String.format("nohup java -jar -Xdebug "
+ "-Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n "
+ "-Dazure.keyvault.uri=%s %s &"
+ " >/log.txt 2>&1",
AZURE_KEYVAULT_URI,
"app.jar"));
vm.runCommand(new RunCommandInput().withCommandId("RunShellScript").withScript(commands));
final ResponseEntity<String> response = curlWithRetry(
String.format("http:
3,
60_000,
String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("key vault value is: {}", response.getBody());
LOGGER.info("--------------------->test virtual machine with MSI over");
} | commands.add("git remote add origin https: | public void keyVaultWithVirtualMachineMSI() {
final VirtualMachine vm = AZURE.virtualMachines().getByResourceGroup(SPRING_RESOURCE_GROUP, VM_NAME);
final String host = vm.getPrimaryPublicIPAddress().ipAddress();
final List<String> commands = new ArrayList<>();
commands.add(String.format("cd /home/%s", VM_USER_USERNAME));
commands.add("mkdir azure-sdk-for-java");
commands.add("cd azure-sdk-for-java");
commands.add("git init");
commands.add("git remote add origin https:
commands.add("git config core.sparsecheckout true");
commands.add("echo sdk/spring > .git/info/sparse-checkout");
commands.add("git pull origin master");
commands.add("cd sdk/spring/");
commands.add("mvn package -Dmaven.test.skip=true");
commands.add("cd azure-spring-boot-test-application/target/");
commands.add(String.format("nohup java -jar -Xdebug "
+ "-Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n "
+ "-Dazure.keyvault.uri=%s %s &"
+ " >/log.txt 2>&1",
AZURE_KEYVAULT_URI,
"app.jar"));
vm.runCommand(new RunCommandInput().withCommandId("RunShellScript").withScript(commands));
final ResponseEntity<String> response = curlWithRetry(
String.format("http:
3,
60_000,
String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("key vault value is: {}", response.getBody());
LOGGER.info("--------------------->test virtual machine with MSI over");
} | class KeyVaultIT {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultIT.class);
private static final String AZURE_KEYVAULT_URI = System.getenv("AZURE_KEYVAULT_URI");
private static final String KEY_VAULT_SECRET_VALUE = System.getenv("KEY_VAULT_SECRET_VALUE");
private static final String KEY_VAULT_SECRET_NAME = System.getenv("KEY_VAULT_SECRET_NAME");
private static final String SPRING_RESOURCE_GROUP = System.getenv("SPRING_RESOURCE_GROUP");
private static final String APP_SERVICE_NAME = System.getenv("APP_SERVICE_NAME");
private static final String VM_NAME = System.getenv("VM_NAME");
private static final String VM_USER_USERNAME = System.getenv("VM_USER_USERNAME");
private static final String VM_USER_PASSWORD = System.getenv("VM_USER_PASSWORD");
private static final int DEFAULT_MAX_RETRY_TIMES = 3;
private static final Azure AZURE;
private static final ClientSecretAccess CLIENT_SECRET_ACCESS;
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
static {
CLIENT_SECRET_ACCESS = ClientSecretAccess.load();
AZURE = Azure.authenticate(CLIENT_SECRET_ACCESS.credentials())
.withSubscription(CLIENT_SECRET_ACCESS.subscription());
}
@Test
public void keyVaultAsPropertySource() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
final ConfigurableApplicationContext dummy = app.start("dummy");
final ConfigurableEnvironment environment = dummy.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
for (final PropertySource<?> propertySource : propertySources) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultAsPropertySourceWithSpecificKeys() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
app.property("azure.keyvault.secret-keys", KEY_VAULT_SECRET_NAME);
LOGGER.info("====" + KEY_VAULT_SECRET_NAME );
app.start();
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultWithAppServiceMSI() {
final WebApp webApp = AZURE
.webApps()
.getByResourceGroup(SPRING_RESOURCE_GROUP, APP_SERVICE_NAME);
final MavenBasedProject app = new MavenBasedProject("../azure-spring-boot-test-application");
app.packageUp();
int retryCount = 0;
final File zipFile = new File(app.zipFile());
while (retryCount < DEFAULT_MAX_RETRY_TIMES) {
retryCount += 1;
try {
webApp.zipDeploy(zipFile);
LOGGER.info(String.format("Deployed the artifact to https:
break;
} catch (Exception e) {
LOGGER.error(String.format("Exception occurred when deploying the zip package: %s, "
+ "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES));
}
}
LOGGER.info("restarting app service...");
webApp.restart();
LOGGER.info("restarting app service finished...");
final String resourceUrl = "https:
final ResponseEntity<String> response = curlWithRetry(resourceUrl, 3, 120_000, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("--------------------->test app service with MSI over");
}
@Test
private static <T> ResponseEntity<T> curlWithRetry(String resourceUrl,
final int retryTimes,
int sleepMills,
Class<T> clazz) {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ResponseEntity<T> response = ResponseEntity.of(Optional.empty());
int rt = retryTimes;
while (rt-- > 0 && httpStatus != HttpStatus.OK) {
SdkContext.sleep(sleepMills);
LOGGER.info("CURLing " + resourceUrl);
try {
response = REST_TEMPLATE.getForEntity(resourceUrl, clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
httpStatus = response.getStatusCode();
}
return response;
}
@SpringBootApplication
public static class DumbApp {
}
} | class KeyVaultIT {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultIT.class);
private static final String AZURE_KEYVAULT_URI = System.getenv("AZURE_KEYVAULT_URI");
private static final String KEY_VAULT_SECRET_VALUE = System.getenv("KEY_VAULT_SECRET_VALUE");
private static final String KEY_VAULT_SECRET_NAME = System.getenv("KEY_VAULT_SECRET_NAME");
private static final String SPRING_RESOURCE_GROUP = System.getenv("SPRING_RESOURCE_GROUP");
private static final String APP_SERVICE_NAME = System.getenv("APP_SERVICE_NAME");
private static final String VM_NAME = System.getenv("VM_NAME");
private static final String VM_USER_USERNAME = System.getenv("VM_USER_USERNAME");
private static final String VM_USER_PASSWORD = System.getenv("VM_USER_PASSWORD");
private static final int DEFAULT_MAX_RETRY_TIMES = 3;
private static final Azure AZURE;
private static final ClientSecretAccess CLIENT_SECRET_ACCESS;
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
static {
CLIENT_SECRET_ACCESS = ClientSecretAccess.load();
AZURE = Azure.authenticate(CLIENT_SECRET_ACCESS.credentials())
.withSubscription(CLIENT_SECRET_ACCESS.subscription());
}
@Test
public void keyVaultAsPropertySource() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
final ConfigurableApplicationContext dummy = app.start("dummy");
final ConfigurableEnvironment environment = dummy.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
for (final PropertySource<?> propertySource : propertySources) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultAsPropertySourceWithSpecificKeys() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
app.property("azure.keyvault.secret-keys", KEY_VAULT_SECRET_NAME);
LOGGER.info("====" + KEY_VAULT_SECRET_NAME );
app.start();
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultWithAppServiceMSI() {
final WebApp webApp = AZURE
.webApps()
.getByResourceGroup(SPRING_RESOURCE_GROUP, APP_SERVICE_NAME);
final MavenBasedProject app = new MavenBasedProject("../azure-spring-boot-test-application");
app.packageUp();
int retryCount = 0;
final File zipFile = new File(app.zipFile());
while (retryCount < DEFAULT_MAX_RETRY_TIMES) {
retryCount += 1;
try {
webApp.zipDeploy(zipFile);
LOGGER.info(String.format("Deployed the artifact to https:
break;
} catch (Exception e) {
LOGGER.error(String.format("Exception occurred when deploying the zip package: %s, "
+ "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES));
}
}
LOGGER.info("restarting app service...");
webApp.restart();
LOGGER.info("restarting app service finished...");
final String resourceUrl = "https:
final ResponseEntity<String> response = curlWithRetry(resourceUrl, 3, 120_000, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("--------------------->test app service with MSI over");
}
@Test
private static <T> ResponseEntity<T> curlWithRetry(String resourceUrl,
final int retryTimes,
int sleepMills,
Class<T> clazz) {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ResponseEntity<T> response = ResponseEntity.of(Optional.empty());
int rt = retryTimes;
while (rt-- > 0 && httpStatus != HttpStatus.OK) {
SdkContext.sleep(sleepMills);
LOGGER.info("CURLing " + resourceUrl);
try {
response = REST_TEMPLATE.getForEntity(resourceUrl, clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
httpStatus = response.getStatusCode();
}
return response;
}
@SpringBootApplication
public static class DumbApp {
}
} |
So why do we choose to pull the project from GitHub instead of pushing it? | public void keyVaultWithVirtualMachineMSI() {
final VirtualMachine vm = AZURE.virtualMachines().getByResourceGroup(SPRING_RESOURCE_GROUP, VM_NAME);
final String host = vm.getPrimaryPublicIPAddress().ipAddress();
final List<String> commands = new ArrayList<>();
commands.add(String.format("cd /home/%s", VM_USER_USERNAME));
commands.add("mkdir azure-sdk-for-java");
commands.add("cd azure-sdk-for-java");
commands.add("git init");
commands.add("git remote add origin https:
commands.add("git config core.sparsecheckout true");
commands.add("echo sdk/spring > .git/info/sparse-checkout");
commands.add("git pull origin master");
commands.add("cd sdk/spring/");
commands.add("mvn package -Dmaven.test.skip=true");
commands.add("cd azure-spring-boot-test-application/target/");
commands.add(String.format("nohup java -jar -Xdebug "
+ "-Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n "
+ "-Dazure.keyvault.uri=%s %s &"
+ " >/log.txt 2>&1",
AZURE_KEYVAULT_URI,
"app.jar"));
vm.runCommand(new RunCommandInput().withCommandId("RunShellScript").withScript(commands));
final ResponseEntity<String> response = curlWithRetry(
String.format("http:
3,
60_000,
String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("key vault value is: {}", response.getBody());
LOGGER.info("--------------------->test virtual machine with MSI over");
} | commands.add("git remote add origin https: | public void keyVaultWithVirtualMachineMSI() {
final VirtualMachine vm = AZURE.virtualMachines().getByResourceGroup(SPRING_RESOURCE_GROUP, VM_NAME);
final String host = vm.getPrimaryPublicIPAddress().ipAddress();
final List<String> commands = new ArrayList<>();
commands.add(String.format("cd /home/%s", VM_USER_USERNAME));
commands.add("mkdir azure-sdk-for-java");
commands.add("cd azure-sdk-for-java");
commands.add("git init");
commands.add("git remote add origin https:
commands.add("git config core.sparsecheckout true");
commands.add("echo sdk/spring > .git/info/sparse-checkout");
commands.add("git pull origin master");
commands.add("cd sdk/spring/");
commands.add("mvn package -Dmaven.test.skip=true");
commands.add("cd azure-spring-boot-test-application/target/");
commands.add(String.format("nohup java -jar -Xdebug "
+ "-Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n "
+ "-Dazure.keyvault.uri=%s %s &"
+ " >/log.txt 2>&1",
AZURE_KEYVAULT_URI,
"app.jar"));
vm.runCommand(new RunCommandInput().withCommandId("RunShellScript").withScript(commands));
final ResponseEntity<String> response = curlWithRetry(
String.format("http:
3,
60_000,
String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("key vault value is: {}", response.getBody());
LOGGER.info("--------------------->test virtual machine with MSI over");
} | class KeyVaultIT {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultIT.class);
private static final String AZURE_KEYVAULT_URI = System.getenv("AZURE_KEYVAULT_URI");
private static final String KEY_VAULT_SECRET_VALUE = System.getenv("KEY_VAULT_SECRET_VALUE");
private static final String KEY_VAULT_SECRET_NAME = System.getenv("KEY_VAULT_SECRET_NAME");
private static final String SPRING_RESOURCE_GROUP = System.getenv("SPRING_RESOURCE_GROUP");
private static final String APP_SERVICE_NAME = System.getenv("APP_SERVICE_NAME");
private static final String VM_NAME = System.getenv("VM_NAME");
private static final String VM_USER_USERNAME = System.getenv("VM_USER_USERNAME");
private static final String VM_USER_PASSWORD = System.getenv("VM_USER_PASSWORD");
private static final int DEFAULT_MAX_RETRY_TIMES = 3;
private static final Azure AZURE;
private static final ClientSecretAccess CLIENT_SECRET_ACCESS;
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
static {
CLIENT_SECRET_ACCESS = ClientSecretAccess.load();
AZURE = Azure.authenticate(CLIENT_SECRET_ACCESS.credentials())
.withSubscription(CLIENT_SECRET_ACCESS.subscription());
}
@Test
public void keyVaultAsPropertySource() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
final ConfigurableApplicationContext dummy = app.start("dummy");
final ConfigurableEnvironment environment = dummy.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
for (final PropertySource<?> propertySource : propertySources) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultAsPropertySourceWithSpecificKeys() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
app.property("azure.keyvault.secret-keys", KEY_VAULT_SECRET_NAME);
LOGGER.info("====" + KEY_VAULT_SECRET_NAME );
app.start();
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultWithAppServiceMSI() {
final WebApp webApp = AZURE
.webApps()
.getByResourceGroup(SPRING_RESOURCE_GROUP, APP_SERVICE_NAME);
final MavenBasedProject app = new MavenBasedProject("../azure-spring-boot-test-application");
app.packageUp();
int retryCount = 0;
final File zipFile = new File(app.zipFile());
while (retryCount < DEFAULT_MAX_RETRY_TIMES) {
retryCount += 1;
try {
webApp.zipDeploy(zipFile);
LOGGER.info(String.format("Deployed the artifact to https:
break;
} catch (Exception e) {
LOGGER.error(String.format("Exception occurred when deploying the zip package: %s, "
+ "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES));
}
}
LOGGER.info("restarting app service...");
webApp.restart();
LOGGER.info("restarting app service finished...");
final String resourceUrl = "https:
final ResponseEntity<String> response = curlWithRetry(resourceUrl, 3, 120_000, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("--------------------->test app service with MSI over");
}
@Test
private static <T> ResponseEntity<T> curlWithRetry(String resourceUrl,
final int retryTimes,
int sleepMills,
Class<T> clazz) {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ResponseEntity<T> response = ResponseEntity.of(Optional.empty());
int rt = retryTimes;
while (rt-- > 0 && httpStatus != HttpStatus.OK) {
SdkContext.sleep(sleepMills);
LOGGER.info("CURLing " + resourceUrl);
try {
response = REST_TEMPLATE.getForEntity(resourceUrl, clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
httpStatus = response.getStatusCode();
}
return response;
}
@SpringBootApplication
public static class DumbApp {
}
} | class KeyVaultIT {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultIT.class);
private static final String AZURE_KEYVAULT_URI = System.getenv("AZURE_KEYVAULT_URI");
private static final String KEY_VAULT_SECRET_VALUE = System.getenv("KEY_VAULT_SECRET_VALUE");
private static final String KEY_VAULT_SECRET_NAME = System.getenv("KEY_VAULT_SECRET_NAME");
private static final String SPRING_RESOURCE_GROUP = System.getenv("SPRING_RESOURCE_GROUP");
private static final String APP_SERVICE_NAME = System.getenv("APP_SERVICE_NAME");
private static final String VM_NAME = System.getenv("VM_NAME");
private static final String VM_USER_USERNAME = System.getenv("VM_USER_USERNAME");
private static final String VM_USER_PASSWORD = System.getenv("VM_USER_PASSWORD");
private static final int DEFAULT_MAX_RETRY_TIMES = 3;
private static final Azure AZURE;
private static final ClientSecretAccess CLIENT_SECRET_ACCESS;
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
static {
CLIENT_SECRET_ACCESS = ClientSecretAccess.load();
AZURE = Azure.authenticate(CLIENT_SECRET_ACCESS.credentials())
.withSubscription(CLIENT_SECRET_ACCESS.subscription());
}
@Test
public void keyVaultAsPropertySource() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
final ConfigurableApplicationContext dummy = app.start("dummy");
final ConfigurableEnvironment environment = dummy.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
for (final PropertySource<?> propertySource : propertySources) {
System.out.println("name = " + propertySource.getName() + "\nsource = " + propertySource
.getSource().getClass() + "\n");
}
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultAsPropertySourceWithSpecificKeys() {
try (AppRunner app = new AppRunner(DumbApp.class)) {
app.property("azure.keyvault.enabled", "true");
app.property("azure.keyvault.uri", AZURE_KEYVAULT_URI);
app.property("azure.keyvault.client-id", CLIENT_SECRET_ACCESS.clientId());
app.property("azure.keyvault.client-key", CLIENT_SECRET_ACCESS.clientSecret());
app.property("azure.keyvault.tenant-id", CLIENT_SECRET_ACCESS.tenantId());
app.property("azure.keyvault.secret-keys", KEY_VAULT_SECRET_NAME);
LOGGER.info("====" + KEY_VAULT_SECRET_NAME );
app.start();
assertEquals(KEY_VAULT_SECRET_VALUE, app.getProperty(KEY_VAULT_SECRET_NAME));
LOGGER.info("--------------------->test over");
}
}
@Test
public void keyVaultWithAppServiceMSI() {
final WebApp webApp = AZURE
.webApps()
.getByResourceGroup(SPRING_RESOURCE_GROUP, APP_SERVICE_NAME);
final MavenBasedProject app = new MavenBasedProject("../azure-spring-boot-test-application");
app.packageUp();
int retryCount = 0;
final File zipFile = new File(app.zipFile());
while (retryCount < DEFAULT_MAX_RETRY_TIMES) {
retryCount += 1;
try {
webApp.zipDeploy(zipFile);
LOGGER.info(String.format("Deployed the artifact to https:
break;
} catch (Exception e) {
LOGGER.error(String.format("Exception occurred when deploying the zip package: %s, "
+ "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES));
}
}
LOGGER.info("restarting app service...");
webApp.restart();
LOGGER.info("restarting app service finished...");
final String resourceUrl = "https:
final ResponseEntity<String> response = curlWithRetry(resourceUrl, 3, 120_000, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(KEY_VAULT_SECRET_VALUE, response.getBody());
LOGGER.info("--------------------->test app service with MSI over");
}
@Test
private static <T> ResponseEntity<T> curlWithRetry(String resourceUrl,
final int retryTimes,
int sleepMills,
Class<T> clazz) {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
ResponseEntity<T> response = ResponseEntity.of(Optional.empty());
int rt = retryTimes;
while (rt-- > 0 && httpStatus != HttpStatus.OK) {
SdkContext.sleep(sleepMills);
LOGGER.info("CURLing " + resourceUrl);
try {
response = REST_TEMPLATE.getForEntity(resourceUrl, clazz);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
httpStatus = response.getStatusCode();
}
return response;
}
@SpringBootApplication
public static class DumbApp {
}
} |
I like this, we should split the test-setup part in other tests as well | public void publishTelemetryLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient client = getAsyncClient(httpClient, serviceVersion);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsAndTwins(client, wifiModelId, roomWithWifiModelId, roomWithWifiTwinId);
PublishTelemetryRequestOptions telemetryRequestOptions = new PublishTelemetryRequestOptions().setMessageId(testResourceNamer.randomUuid());
StepVerifier.create(client.publishTelemetryWithResponse(
roomWithWifiTwinId,
"{\"Telemetry1\": 5}",
telemetryRequestOptions,
Context.NONE))
.assertNext(createResponse -> assertThat(createResponse.getStatusCode())
.as("Publish telemetry succeeds")
.isEqualTo(HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
PublishTelemetryRequestOptions componentTelemetryRequestOptions = new PublishTelemetryRequestOptions().setMessageId(testResourceNamer.randomUuid());
Dictionary<String, Integer> telemetryPayload = new Hashtable<>();
telemetryPayload.put("ComponentTelemetry1", 9);
String telemetryStringPayload = new ObjectMapper().writeValueAsString(telemetryPayload);
StepVerifier.create(client.publishComponentTelemetryWithResponse(
roomWithWifiTwinId,
TestAssetDefaults.WIFI_COMPONENT_NAME,
telemetryStringPayload,
componentTelemetryRequestOptions,
Context.NONE))
.assertNext(createResponse -> assertThat(createResponse.getStatusCode())
.as("Publish telemetry succeeds")
.isEqualTo(HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
}
catch (Exception ex) {
fail("Failure in executing a step in the test case", ex);
}
finally {
try {
if (roomWithWifiTwinId != null){
client.deleteDigitalTwin(roomWithWifiTwinId).block();
}
if (roomWithWifiModelId != null){
client.deleteModel(roomWithWifiModelId).block();
}
if(wifiModelId != null){
client.deleteModel(wifiModelId).block();
}
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | createModelsAndTwins(client, wifiModelId, roomWithWifiModelId, roomWithWifiTwinId); | public void publishTelemetryLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient client = getAsyncClient(httpClient, serviceVersion);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsAndTwins(client, wifiModelId, roomWithWifiModelId, roomWithWifiTwinId);
PublishTelemetryRequestOptions telemetryRequestOptions = new PublishTelemetryRequestOptions().setMessageId(testResourceNamer.randomUuid());
StepVerifier.create(client.publishTelemetryWithResponse(
roomWithWifiTwinId,
"{\"Telemetry1\": 5}",
telemetryRequestOptions,
Context.NONE))
.assertNext(createResponse -> assertThat(createResponse.getStatusCode())
.as("Publish telemetry succeeds")
.isEqualTo(HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
PublishTelemetryRequestOptions componentTelemetryRequestOptions = new PublishTelemetryRequestOptions().setMessageId(testResourceNamer.randomUuid());
Dictionary<String, Integer> telemetryPayload = new Hashtable<>();
telemetryPayload.put("ComponentTelemetry1", 9);
String telemetryStringPayload = new ObjectMapper().writeValueAsString(telemetryPayload);
StepVerifier.create(client.publishComponentTelemetryWithResponse(
roomWithWifiTwinId,
TestAssetDefaults.WIFI_COMPONENT_NAME,
telemetryStringPayload,
componentTelemetryRequestOptions,
Context.NONE))
.assertNext(createResponse -> assertThat(createResponse.getStatusCode())
.as("Publish telemetry succeeds")
.isEqualTo(HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
}
catch (Exception ex) {
fail("Failure in executing a step in the test case", ex);
}
finally {
try {
if (roomWithWifiTwinId != null){
client.deleteDigitalTwin(roomWithWifiTwinId).block();
}
if (roomWithWifiModelId != null){
client.deleteModel(roomWithWifiModelId).block();
}
if(wifiModelId != null){
client.deleteModel(wifiModelId).block();
}
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | class PublishTelemetryAsyncTests extends PublishTelemetryTestBase {
private final ClientLogger logger = new ClientLogger(PublishTelemetryAsyncTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
private void createModelsAndTwins(DigitalTwinsAsyncClient asyncClient, String wifiModelId, String roomWithWifiModelId, String roomWithWifiTwinId){
String wifiModelPayload = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String roomWithWifiModelPayload = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, TestAssetDefaults.WIFI_COMPONENT_NAME);
StepVerifier
.create(asyncClient.createModels(new ArrayList<>(Arrays.asList(wifiModelPayload, roomWithWifiModelPayload))))
.assertNext(createResponseList -> logger.info("Created {} models successfully", createResponseList.size()))
.verifyComplete();
String roomWithWifiTwinPayload = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, TestAssetDefaults.WIFI_COMPONENT_NAME);
StepVerifier
.create(asyncClient.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwinPayload))
.assertNext(createResponse -> logger.info("Created {} digitalTwin successfully", createResponse))
.verifyComplete();
}
} | class PublishTelemetryAsyncTests extends PublishTelemetryTestBase {
private final ClientLogger logger = new ClientLogger(PublishTelemetryAsyncTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
private void createModelsAndTwins(DigitalTwinsAsyncClient asyncClient, String wifiModelId, String roomWithWifiModelId, String roomWithWifiTwinId){
String wifiModelPayload = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String roomWithWifiModelPayload = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, TestAssetDefaults.WIFI_COMPONENT_NAME);
StepVerifier
.create(asyncClient.createModels(new ArrayList<>(Arrays.asList(wifiModelPayload, roomWithWifiModelPayload))))
.assertNext(createResponseList -> logger.info("Created {} models successfully", createResponseList.size()))
.verifyComplete();
String roomWithWifiTwinPayload = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, TestAssetDefaults.WIFI_COMPONENT_NAME);
StepVerifier
.create(asyncClient.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwinPayload))
.assertNext(createResponse -> logger.info("Created {} digitalTwin successfully", createResponse))
.verifyComplete();
}
} |
I am planning to do another round of cleanup to make things a bit more consistent , I will address this later during the code cleanup ;) | public void publishTelemetryLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient client = getAsyncClient(httpClient, serviceVersion);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsAndTwins(client, wifiModelId, roomWithWifiModelId, roomWithWifiTwinId);
PublishTelemetryRequestOptions telemetryRequestOptions = new PublishTelemetryRequestOptions().setMessageId(testResourceNamer.randomUuid());
StepVerifier.create(client.publishTelemetryWithResponse(
roomWithWifiTwinId,
"{\"Telemetry1\": 5}",
telemetryRequestOptions,
Context.NONE))
.assertNext(createResponse -> assertThat(createResponse.getStatusCode())
.as("Publish telemetry succeeds")
.isEqualTo(HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
PublishTelemetryRequestOptions componentTelemetryRequestOptions = new PublishTelemetryRequestOptions().setMessageId(testResourceNamer.randomUuid());
Dictionary<String, Integer> telemetryPayload = new Hashtable<>();
telemetryPayload.put("ComponentTelemetry1", 9);
String telemetryStringPayload = new ObjectMapper().writeValueAsString(telemetryPayload);
StepVerifier.create(client.publishComponentTelemetryWithResponse(
roomWithWifiTwinId,
TestAssetDefaults.WIFI_COMPONENT_NAME,
telemetryStringPayload,
componentTelemetryRequestOptions,
Context.NONE))
.assertNext(createResponse -> assertThat(createResponse.getStatusCode())
.as("Publish telemetry succeeds")
.isEqualTo(HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
}
catch (Exception ex) {
fail("Failure in executing a step in the test case", ex);
}
finally {
try {
if (roomWithWifiTwinId != null){
client.deleteDigitalTwin(roomWithWifiTwinId).block();
}
if (roomWithWifiModelId != null){
client.deleteModel(roomWithWifiModelId).block();
}
if(wifiModelId != null){
client.deleteModel(wifiModelId).block();
}
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | createModelsAndTwins(client, wifiModelId, roomWithWifiModelId, roomWithWifiTwinId); | public void publishTelemetryLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient client = getAsyncClient(httpClient, serviceVersion);
String wifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_WITH_WIFI_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomWithWifiTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_WITH_WIFI_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
createModelsAndTwins(client, wifiModelId, roomWithWifiModelId, roomWithWifiTwinId);
PublishTelemetryRequestOptions telemetryRequestOptions = new PublishTelemetryRequestOptions().setMessageId(testResourceNamer.randomUuid());
StepVerifier.create(client.publishTelemetryWithResponse(
roomWithWifiTwinId,
"{\"Telemetry1\": 5}",
telemetryRequestOptions,
Context.NONE))
.assertNext(createResponse -> assertThat(createResponse.getStatusCode())
.as("Publish telemetry succeeds")
.isEqualTo(HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
PublishTelemetryRequestOptions componentTelemetryRequestOptions = new PublishTelemetryRequestOptions().setMessageId(testResourceNamer.randomUuid());
Dictionary<String, Integer> telemetryPayload = new Hashtable<>();
telemetryPayload.put("ComponentTelemetry1", 9);
String telemetryStringPayload = new ObjectMapper().writeValueAsString(telemetryPayload);
StepVerifier.create(client.publishComponentTelemetryWithResponse(
roomWithWifiTwinId,
TestAssetDefaults.WIFI_COMPONENT_NAME,
telemetryStringPayload,
componentTelemetryRequestOptions,
Context.NONE))
.assertNext(createResponse -> assertThat(createResponse.getStatusCode())
.as("Publish telemetry succeeds")
.isEqualTo(HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
}
catch (Exception ex) {
fail("Failure in executing a step in the test case", ex);
}
finally {
try {
if (roomWithWifiTwinId != null){
client.deleteDigitalTwin(roomWithWifiTwinId).block();
}
if (roomWithWifiModelId != null){
client.deleteModel(roomWithWifiModelId).block();
}
if(wifiModelId != null){
client.deleteModel(wifiModelId).block();
}
}
catch (Exception ex) {
fail("Test cleanup failed", ex);
}
}
} | class PublishTelemetryAsyncTests extends PublishTelemetryTestBase {
private final ClientLogger logger = new ClientLogger(PublishTelemetryAsyncTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
private void createModelsAndTwins(DigitalTwinsAsyncClient asyncClient, String wifiModelId, String roomWithWifiModelId, String roomWithWifiTwinId){
String wifiModelPayload = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String roomWithWifiModelPayload = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, TestAssetDefaults.WIFI_COMPONENT_NAME);
StepVerifier
.create(asyncClient.createModels(new ArrayList<>(Arrays.asList(wifiModelPayload, roomWithWifiModelPayload))))
.assertNext(createResponseList -> logger.info("Created {} models successfully", createResponseList.size()))
.verifyComplete();
String roomWithWifiTwinPayload = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, TestAssetDefaults.WIFI_COMPONENT_NAME);
StepVerifier
.create(asyncClient.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwinPayload))
.assertNext(createResponse -> logger.info("Created {} digitalTwin successfully", createResponse))
.verifyComplete();
}
} | class PublishTelemetryAsyncTests extends PublishTelemetryTestBase {
private final ClientLogger logger = new ClientLogger(PublishTelemetryAsyncTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
private void createModelsAndTwins(DigitalTwinsAsyncClient asyncClient, String wifiModelId, String roomWithWifiModelId, String roomWithWifiTwinId){
String wifiModelPayload = TestAssetsHelper.getWifiModelPayload(wifiModelId);
String roomWithWifiModelPayload = TestAssetsHelper.getRoomWithWifiModelPayload(roomWithWifiModelId, wifiModelId, TestAssetDefaults.WIFI_COMPONENT_NAME);
StepVerifier
.create(asyncClient.createModels(new ArrayList<>(Arrays.asList(wifiModelPayload, roomWithWifiModelPayload))))
.assertNext(createResponseList -> logger.info("Created {} models successfully", createResponseList.size()))
.verifyComplete();
String roomWithWifiTwinPayload = TestAssetsHelper.getRoomWithWifiTwinPayload(roomWithWifiModelId, TestAssetDefaults.WIFI_COMPONENT_NAME);
StepVerifier
.create(asyncClient.createDigitalTwin(roomWithWifiTwinId, roomWithWifiTwinPayload))
.assertNext(createResponse -> logger.info("Created {} digitalTwin successfully", createResponse))
.verifyComplete();
}
} |
Did we remove the extra deserialization to Object that was happening in the CL for these APIs? | public static void runPublishTelemetrySample() throws JsonProcessingException {
ConsoleLogger.printHeader("Telemetry Samples");
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TEMPORARY_COMPONENT_MODEL_PREFIX, client, randomIntegerStringGenerator);
String modelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TEMPORARY_MODEL_PREFIX, client, randomIntegerStringGenerator);
String digitalTwinId = UniqueIdHelper.getUniqueDigitalTwinId(SamplesConstants.TEMPORARY_TWIN_PREFIX, client, randomIntegerStringGenerator);
String newComponentModelPayload = SamplesConstants.TEMPORARY_COMPONENT_MODEL_PAYLOAD
.replace(SamplesConstants.COMPONENT_ID, componentModelId);
String newModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_COMPONENT_PAYLOAD
.replace(SamplesConstants.MODEL_ID, modelId)
.replace(SamplesConstants.COMPONENT_ID, componentModelId);
List<String> modelsList = new ArrayList<>(Arrays.asList(newComponentModelPayload, newModelPayload));
ConsoleLogger.printHeader("Create Models");
List<ModelData> modelList = client.createModels(modelsList);
for (ModelData model : modelList) {
ConsoleLogger.print("Created model: " + model.getId());
}
ConsoleLogger.printHeader("Create DigitalTwin");
String twinPayload = SamplesConstants.TEMPORARY_TWIN_PAYLOAD
.replace(SamplesConstants.MODEL_ID, modelId);
client.createDigitalTwin(digitalTwinId, twinPayload);
ConsoleLogger.printSuccess("Created digital twin " + digitalTwinId);
try
{
ConsoleLogger.printHeader("Publish Telemetry");
client.publishTelemetry(digitalTwinId, "{\"Telemetry1\": 5}");
ConsoleLogger.print("Published telemetry message to twin " + digitalTwinId);
ConsoleLogger.printHeader("Publish Component Telemetry");
PublishTelemetryRequestOptions componentTelemetryRequestOptions = new PublishTelemetryRequestOptions();
Dictionary<String, Integer> telemetryPayload = new Hashtable<>();
telemetryPayload.put("ComponentTelemetry1", 9);
String telemetryStringPayload = new ObjectMapper().writeValueAsString(telemetryPayload);
Response<Void> publishComponentTelemetryResponse = client.publishComponentTelemetryWithResponse(
digitalTwinId,
"Component1",
telemetryStringPayload,
componentTelemetryRequestOptions,
Context.NONE);
ConsoleLogger.printSuccess("Published component telemetry message to twin " + digitalTwinId);
}
catch (Exception ex)
{
ConsoleLogger.printFatal("Failed to publish a telemetry message due to:\n" + ex.getMessage());
}
try
{
client.deleteDigitalTwin(digitalTwinId);
client.deleteModel(modelId);
client.deleteModel(componentModelId);
}
catch (ErrorResponseException ex)
{
if (ex.getResponse().getStatusCode() == HttpsURLConnection.HTTP_NOT_FOUND) {
ConsoleLogger.printWarning("Digital twin or models do not exist.");
System.exit(1);
}
ConsoleLogger.printFatal("Failed to delete due to:\n" + ex.getMessage());
}
} | telemetryStringPayload, | public static void runPublishTelemetrySample() throws JsonProcessingException {
ConsoleLogger.printHeader("Telemetry Samples");
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TEMPORARY_COMPONENT_MODEL_PREFIX, client, randomIntegerStringGenerator);
String modelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TEMPORARY_MODEL_PREFIX, client, randomIntegerStringGenerator);
String digitalTwinId = UniqueIdHelper.getUniqueDigitalTwinId(SamplesConstants.TEMPORARY_TWIN_PREFIX, client, randomIntegerStringGenerator);
String newComponentModelPayload = SamplesConstants.TEMPORARY_COMPONENT_MODEL_PAYLOAD
.replace(SamplesConstants.COMPONENT_ID, componentModelId);
String newModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_COMPONENT_PAYLOAD
.replace(SamplesConstants.MODEL_ID, modelId)
.replace(SamplesConstants.COMPONENT_ID, componentModelId);
List<String> modelsList = new ArrayList<>(Arrays.asList(newComponentModelPayload, newModelPayload));
ConsoleLogger.printHeader("Create Models");
List<ModelData> modelList = client.createModels(modelsList);
for (ModelData model : modelList) {
ConsoleLogger.print("Created model: " + model.getId());
}
ConsoleLogger.printHeader("Create DigitalTwin");
String twinPayload = SamplesConstants.TEMPORARY_TWIN_PAYLOAD
.replace(SamplesConstants.MODEL_ID, modelId);
client.createDigitalTwin(digitalTwinId, twinPayload);
ConsoleLogger.printSuccess("Created digital twin " + digitalTwinId);
try
{
ConsoleLogger.printHeader("Publish Telemetry");
client.publishTelemetry(digitalTwinId, "{\"Telemetry1\": 5}");
ConsoleLogger.print("Published telemetry message to twin " + digitalTwinId);
ConsoleLogger.printHeader("Publish Component Telemetry");
PublishTelemetryRequestOptions componentTelemetryRequestOptions = new PublishTelemetryRequestOptions();
Dictionary<String, Integer> telemetryPayload = new Hashtable<>();
telemetryPayload.put("ComponentTelemetry1", 9);
String telemetryStringPayload = new ObjectMapper().writeValueAsString(telemetryPayload);
Response<Void> publishComponentTelemetryResponse = client.publishComponentTelemetryWithResponse(
digitalTwinId,
"Component1",
telemetryStringPayload,
componentTelemetryRequestOptions,
Context.NONE);
ConsoleLogger.printSuccess("Published component telemetry message to twin " + digitalTwinId);
}
catch (Exception ex)
{
ConsoleLogger.printFatal("Failed to publish a telemetry message due to:\n" + ex.getMessage());
}
try
{
client.deleteDigitalTwin(digitalTwinId);
client.deleteModel(modelId);
client.deleteModel(componentModelId);
}
catch (ErrorResponseException ex)
{
if (ex.getResponse().getStatusCode() == HttpsURLConnection.HTTP_NOT_FOUND) {
ConsoleLogger.printWarning("Digital twin or models do not exist.");
System.exit(1);
}
ConsoleLogger.printFatal("Failed to delete due to:\n" + ex.getMessage());
}
} | class PublishTelemetrySyncSamples {
private static DigitalTwinsClient client;
private static final ObjectMapper mapper = new ObjectMapper();
public static Function<Integer, String> randomIntegerStringGenerator = (maxLength) -> {
int randInt = new Random().nextInt((int)Math.pow(10, 8) - 1) + 1;
return String.valueOf(randInt);
};
public static void main(String[] args) throws IOException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runPublishTelemetrySample();
}
} | class PublishTelemetrySyncSamples {
private static DigitalTwinsClient client;
private static final ObjectMapper mapper = new ObjectMapper();
public static Function<Integer, String> randomIntegerStringGenerator = (maxLength) -> {
int randInt = new Random().nextInt((int)Math.pow(10, 8) - 1) + 1;
return String.valueOf(randInt);
};
public static void main(String[] args) throws IOException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runPublishTelemetrySample();
}
} |
Nope, seems I have forgotten all about it | public static void runPublishTelemetrySample() throws JsonProcessingException {
ConsoleLogger.printHeader("Telemetry Samples");
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TEMPORARY_COMPONENT_MODEL_PREFIX, client, randomIntegerStringGenerator);
String modelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TEMPORARY_MODEL_PREFIX, client, randomIntegerStringGenerator);
String digitalTwinId = UniqueIdHelper.getUniqueDigitalTwinId(SamplesConstants.TEMPORARY_TWIN_PREFIX, client, randomIntegerStringGenerator);
String newComponentModelPayload = SamplesConstants.TEMPORARY_COMPONENT_MODEL_PAYLOAD
.replace(SamplesConstants.COMPONENT_ID, componentModelId);
String newModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_COMPONENT_PAYLOAD
.replace(SamplesConstants.MODEL_ID, modelId)
.replace(SamplesConstants.COMPONENT_ID, componentModelId);
List<String> modelsList = new ArrayList<>(Arrays.asList(newComponentModelPayload, newModelPayload));
ConsoleLogger.printHeader("Create Models");
List<ModelData> modelList = client.createModels(modelsList);
for (ModelData model : modelList) {
ConsoleLogger.print("Created model: " + model.getId());
}
ConsoleLogger.printHeader("Create DigitalTwin");
String twinPayload = SamplesConstants.TEMPORARY_TWIN_PAYLOAD
.replace(SamplesConstants.MODEL_ID, modelId);
client.createDigitalTwin(digitalTwinId, twinPayload);
ConsoleLogger.printSuccess("Created digital twin " + digitalTwinId);
try
{
ConsoleLogger.printHeader("Publish Telemetry");
client.publishTelemetry(digitalTwinId, "{\"Telemetry1\": 5}");
ConsoleLogger.print("Published telemetry message to twin " + digitalTwinId);
ConsoleLogger.printHeader("Publish Component Telemetry");
PublishTelemetryRequestOptions componentTelemetryRequestOptions = new PublishTelemetryRequestOptions();
Dictionary<String, Integer> telemetryPayload = new Hashtable<>();
telemetryPayload.put("ComponentTelemetry1", 9);
String telemetryStringPayload = new ObjectMapper().writeValueAsString(telemetryPayload);
Response<Void> publishComponentTelemetryResponse = client.publishComponentTelemetryWithResponse(
digitalTwinId,
"Component1",
telemetryStringPayload,
componentTelemetryRequestOptions,
Context.NONE);
ConsoleLogger.printSuccess("Published component telemetry message to twin " + digitalTwinId);
}
catch (Exception ex)
{
ConsoleLogger.printFatal("Failed to publish a telemetry message due to:\n" + ex.getMessage());
}
try
{
client.deleteDigitalTwin(digitalTwinId);
client.deleteModel(modelId);
client.deleteModel(componentModelId);
}
catch (ErrorResponseException ex)
{
if (ex.getResponse().getStatusCode() == HttpsURLConnection.HTTP_NOT_FOUND) {
ConsoleLogger.printWarning("Digital twin or models do not exist.");
System.exit(1);
}
ConsoleLogger.printFatal("Failed to delete due to:\n" + ex.getMessage());
}
} | telemetryStringPayload, | public static void runPublishTelemetrySample() throws JsonProcessingException {
ConsoleLogger.printHeader("Telemetry Samples");
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TEMPORARY_COMPONENT_MODEL_PREFIX, client, randomIntegerStringGenerator);
String modelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TEMPORARY_MODEL_PREFIX, client, randomIntegerStringGenerator);
String digitalTwinId = UniqueIdHelper.getUniqueDigitalTwinId(SamplesConstants.TEMPORARY_TWIN_PREFIX, client, randomIntegerStringGenerator);
String newComponentModelPayload = SamplesConstants.TEMPORARY_COMPONENT_MODEL_PAYLOAD
.replace(SamplesConstants.COMPONENT_ID, componentModelId);
String newModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_COMPONENT_PAYLOAD
.replace(SamplesConstants.MODEL_ID, modelId)
.replace(SamplesConstants.COMPONENT_ID, componentModelId);
List<String> modelsList = new ArrayList<>(Arrays.asList(newComponentModelPayload, newModelPayload));
ConsoleLogger.printHeader("Create Models");
List<ModelData> modelList = client.createModels(modelsList);
for (ModelData model : modelList) {
ConsoleLogger.print("Created model: " + model.getId());
}
ConsoleLogger.printHeader("Create DigitalTwin");
String twinPayload = SamplesConstants.TEMPORARY_TWIN_PAYLOAD
.replace(SamplesConstants.MODEL_ID, modelId);
client.createDigitalTwin(digitalTwinId, twinPayload);
ConsoleLogger.printSuccess("Created digital twin " + digitalTwinId);
try
{
ConsoleLogger.printHeader("Publish Telemetry");
client.publishTelemetry(digitalTwinId, "{\"Telemetry1\": 5}");
ConsoleLogger.print("Published telemetry message to twin " + digitalTwinId);
ConsoleLogger.printHeader("Publish Component Telemetry");
PublishTelemetryRequestOptions componentTelemetryRequestOptions = new PublishTelemetryRequestOptions();
Dictionary<String, Integer> telemetryPayload = new Hashtable<>();
telemetryPayload.put("ComponentTelemetry1", 9);
String telemetryStringPayload = new ObjectMapper().writeValueAsString(telemetryPayload);
Response<Void> publishComponentTelemetryResponse = client.publishComponentTelemetryWithResponse(
digitalTwinId,
"Component1",
telemetryStringPayload,
componentTelemetryRequestOptions,
Context.NONE);
ConsoleLogger.printSuccess("Published component telemetry message to twin " + digitalTwinId);
}
catch (Exception ex)
{
ConsoleLogger.printFatal("Failed to publish a telemetry message due to:\n" + ex.getMessage());
}
try
{
client.deleteDigitalTwin(digitalTwinId);
client.deleteModel(modelId);
client.deleteModel(componentModelId);
}
catch (ErrorResponseException ex)
{
if (ex.getResponse().getStatusCode() == HttpsURLConnection.HTTP_NOT_FOUND) {
ConsoleLogger.printWarning("Digital twin or models do not exist.");
System.exit(1);
}
ConsoleLogger.printFatal("Failed to delete due to:\n" + ex.getMessage());
}
} | class PublishTelemetrySyncSamples {
private static DigitalTwinsClient client;
private static final ObjectMapper mapper = new ObjectMapper();
public static Function<Integer, String> randomIntegerStringGenerator = (maxLength) -> {
int randInt = new Random().nextInt((int)Math.pow(10, 8) - 1) + 1;
return String.valueOf(randInt);
};
public static void main(String[] args) throws IOException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runPublishTelemetrySample();
}
} | class PublishTelemetrySyncSamples {
private static DigitalTwinsClient client;
private static final ObjectMapper mapper = new ObjectMapper();
public static Function<Integer, String> randomIntegerStringGenerator = (maxLength) -> {
int randInt = new Random().nextInt((int)Math.pow(10, 8) - 1) + 1;
return String.valueOf(randInt);
};
public static void main(String[] args) throws IOException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runPublishTelemetrySample();
}
} |
Clarification: Scheduling is to unblock timer-wheel right? Thought: Leaving the choice to consumers is error prone, is it possible to force timer wheel it-self own and schedule on them (Of-course follow-up)? | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirator.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirationExecutor.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirator = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} | |
BacklogItem: gate the validation and detect future regressions. Its a generic comments not just spcific to this change. | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirator.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | requestExpirator.execute(record::expire); | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirationExecutor.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirator = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} |
Is this check required? Wouldn't something other than the accepted response code generate an exception? | public static void runRelationshipsSample() throws JsonProcessingException {
ConsoleLogger.printHeader("RELATIONSHIP SAMPLE");
String sampleBuildingModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.BUILDING_MODEL_ID, client, randomIntegerStringGenerator);
String sampleFloorModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.FLOOR_MODEL_ID, client, randomIntegerStringGenerator);
String buildingTwinId = UniqueIdHelper.getUniqueDigitalTwinId("buildingTwinId", client, randomIntegerStringGenerator);
String floorTwinId = UniqueIdHelper.getUniqueDigitalTwinId("floorTwinId", client, randomIntegerStringGenerator);
final String buildingFloorRelationshipId = "buildingFloorRelationshipId";
String buildingModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_RELATIONSHIP_PAYLOAD
.replace(SamplesConstants.MODEL_ID, sampleBuildingModelId)
.replace(SamplesConstants.MODEL_DISPLAY_NAME, "Building")
.replace(SamplesConstants.RELATIONSHIP_NAME, "contains")
.replace(SamplesConstants.RELATIONSHIP_TARGET_MODEL_ID, sampleFloorModelId);
String floorModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_RELATIONSHIP_PAYLOAD
.replace(SamplesConstants.MODEL_ID, sampleFloorModelId)
.replace(SamplesConstants.MODEL_DISPLAY_NAME, "Floor")
.replace(SamplesConstants.RELATIONSHIP_NAME, "containedIn")
.replace(SamplesConstants.RELATIONSHIP_TARGET_MODEL_ID, sampleBuildingModelId);
List<ModelData> createdModels = client.createModels(new ArrayList<>(Arrays.asList(buildingModelPayload, floorModelPayload)));
for (ModelData model : createdModels) {
ConsoleLogger.print("Created model " + model.getId());
}
BasicDigitalTwin buildingDigitalTwin = new BasicDigitalTwin()
.setId(buildingTwinId)
.setMetadata(new DigitalTwinMetadata()
.setModelId(sampleBuildingModelId));
client.createDigitalTwin(buildingTwinId, mapper.writeValueAsString(buildingDigitalTwin));
ConsoleLogger.print("Created twin" + buildingDigitalTwin.getId());
BasicDigitalTwin floorDigitalTwin = new BasicDigitalTwin()
.setId(floorTwinId)
.setMetadata(new DigitalTwinMetadata()
.setModelId(sampleFloorModelId));
client.createDigitalTwin(floorTwinId, mapper.writeValueAsString(floorDigitalTwin));
ConsoleLogger.print("Created twin" + floorDigitalTwin.getId());
ConsoleLogger.printHeader("Create relationships");
BasicRelationship buildingFloorRelationshipPayload = new BasicRelationship()
.setId(buildingFloorRelationshipId)
.setSourceId(buildingTwinId)
.setTargetId(floorTwinId)
.setName("contains")
.setCustomProperties("Prop1", "Prop1 value")
.setCustomProperties("Prop2", 6);
client.createRelationship(buildingTwinId, buildingFloorRelationshipId, mapper.writeValueAsString(buildingFloorRelationshipPayload));
ConsoleLogger.printSuccess("Created a digital twin relationship "+ buildingFloorRelationshipId + " from twin: " + buildingTwinId + " to twin: " + floorTwinId);
ConsoleLogger.printHeader("Get Relationship");
Response<BasicRelationship> getRelationshipRepsonse = client.getRelationshipWithResponse(
buildingTwinId,
buildingFloorRelationshipId,
BasicRelationship.class,
Context.NONE);
if (getRelationshipRepsonse.getStatusCode() == HttpURLConnection.HTTP_OK) {
BasicRelationship retrievedRelationship = getRelationshipRepsonse.getValue();
ConsoleLogger.printSuccess("Retrieved relationship: " + retrievedRelationship.getId() + " from twin: " + retrievedRelationship.getSourceId() + "\n\t" +
"Prop1: " + retrievedRelationship.getCustomProperties().get("Prop1") + "\n\t" +
"Prop2: " + retrievedRelationship.getCustomProperties().get("Prop2"));
}
ConsoleLogger.printHeader("List relationships");
PagedIterable<BasicRelationship> relationshipPages = client.listRelationships(buildingTwinId, BasicRelationship.class);
for (BasicRelationship relationship : relationshipPages) {
ConsoleLogger.printSuccess("Retrieved relationship: " + relationship.getId() + " with source: " + relationship.getSourceId() + " and target: " + relationship.getTargetId());
}
ConsoleLogger.printHeader("List incoming relationships");
PagedIterable<IncomingRelationship> incomingRelationships = client.listIncomingRelationships(floorTwinId);
for (IncomingRelationship incomingRelationship : incomingRelationships) {
ConsoleLogger.printSuccess("Found an incoming relationship: " + incomingRelationship.getRelationshipId() + " from: " + incomingRelationship.getSourceId());
}
ConsoleLogger.printHeader("Delete relationship");
client.deleteRelationship(buildingTwinId, buildingFloorRelationshipId);
ConsoleLogger.printSuccess("Deleted relationship: " + buildingFloorRelationshipId);
try {
client.deleteDigitalTwin(buildingTwinId);
client.deleteDigitalTwin(floorTwinId);
}
catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to delete digital twin due to" + ex);
}
try {
client.deleteModel(sampleBuildingModelId);
client.deleteModel(sampleFloorModelId);
}
catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to delete models due to" + ex);
}
} | if (getRelationshipRepsonse.getStatusCode() == HttpURLConnection.HTTP_OK) { | public static void runRelationshipsSample() throws JsonProcessingException {
ConsoleLogger.printHeader("RELATIONSHIP SAMPLE");
String sampleBuildingModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.BUILDING_MODEL_ID, client, randomIntegerStringGenerator);
String sampleFloorModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.FLOOR_MODEL_ID, client, randomIntegerStringGenerator);
String buildingTwinId = UniqueIdHelper.getUniqueDigitalTwinId("buildingTwinId", client, randomIntegerStringGenerator);
String floorTwinId = UniqueIdHelper.getUniqueDigitalTwinId("floorTwinId", client, randomIntegerStringGenerator);
final String buildingFloorRelationshipId = "buildingFloorRelationshipId";
String buildingModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_RELATIONSHIP_PAYLOAD
.replace(SamplesConstants.MODEL_ID, sampleBuildingModelId)
.replace(SamplesConstants.MODEL_DISPLAY_NAME, "Building")
.replace(SamplesConstants.RELATIONSHIP_NAME, "contains")
.replace(SamplesConstants.RELATIONSHIP_TARGET_MODEL_ID, sampleFloorModelId);
String floorModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_RELATIONSHIP_PAYLOAD
.replace(SamplesConstants.MODEL_ID, sampleFloorModelId)
.replace(SamplesConstants.MODEL_DISPLAY_NAME, "Floor")
.replace(SamplesConstants.RELATIONSHIP_NAME, "containedIn")
.replace(SamplesConstants.RELATIONSHIP_TARGET_MODEL_ID, sampleBuildingModelId);
List<ModelData> createdModels = client.createModels(new ArrayList<>(Arrays.asList(buildingModelPayload, floorModelPayload)));
for (ModelData model : createdModels) {
ConsoleLogger.print("Created model " + model.getId());
}
BasicDigitalTwin buildingDigitalTwin = new BasicDigitalTwin()
.setId(buildingTwinId)
.setMetadata(new DigitalTwinMetadata()
.setModelId(sampleBuildingModelId));
client.createDigitalTwin(buildingTwinId, mapper.writeValueAsString(buildingDigitalTwin));
ConsoleLogger.print("Created twin" + buildingDigitalTwin.getId());
BasicDigitalTwin floorDigitalTwin = new BasicDigitalTwin()
.setId(floorTwinId)
.setMetadata(new DigitalTwinMetadata()
.setModelId(sampleFloorModelId));
client.createDigitalTwin(floorTwinId, mapper.writeValueAsString(floorDigitalTwin));
ConsoleLogger.print("Created twin" + floorDigitalTwin.getId());
ConsoleLogger.printHeader("Create relationships");
BasicRelationship buildingFloorRelationshipPayload = new BasicRelationship()
.setId(buildingFloorRelationshipId)
.setSourceId(buildingTwinId)
.setTargetId(floorTwinId)
.setName("contains")
.setCustomProperties("Prop1", "Prop1 value")
.setCustomProperties("Prop2", 6);
client.createRelationship(buildingTwinId, buildingFloorRelationshipId, mapper.writeValueAsString(buildingFloorRelationshipPayload));
ConsoleLogger.printSuccess("Created a digital twin relationship "+ buildingFloorRelationshipId + " from twin: " + buildingTwinId + " to twin: " + floorTwinId);
ConsoleLogger.printHeader("Get Relationship");
Response<BasicRelationship> getRelationshipResponse = client.getRelationshipWithResponse(
buildingTwinId,
buildingFloorRelationshipId,
BasicRelationship.class,
Context.NONE);
if (getRelationshipResponse.getStatusCode() == HttpURLConnection.HTTP_OK) {
BasicRelationship retrievedRelationship = getRelationshipResponse.getValue();
ConsoleLogger.printSuccess("Retrieved relationship: " + retrievedRelationship.getId() + " from twin: " + retrievedRelationship.getSourceId() + "\n\t" +
"Prop1: " + retrievedRelationship.getCustomProperties().get("Prop1") + "\n\t" +
"Prop2: " + retrievedRelationship.getCustomProperties().get("Prop2"));
}
ConsoleLogger.printHeader("List relationships");
PagedIterable<BasicRelationship> relationshipPages = client.listRelationships(buildingTwinId, BasicRelationship.class);
for (BasicRelationship relationship : relationshipPages) {
ConsoleLogger.printSuccess("Retrieved relationship: " + relationship.getId() + " with source: " + relationship.getSourceId() + " and target: " + relationship.getTargetId());
}
ConsoleLogger.printHeader("List incoming relationships");
PagedIterable<IncomingRelationship> incomingRelationships = client.listIncomingRelationships(floorTwinId);
for (IncomingRelationship incomingRelationship : incomingRelationships) {
ConsoleLogger.printSuccess("Found an incoming relationship: " + incomingRelationship.getRelationshipId() + " from: " + incomingRelationship.getSourceId());
}
ConsoleLogger.printHeader("Delete relationship");
client.deleteRelationship(buildingTwinId, buildingFloorRelationshipId);
ConsoleLogger.printSuccess("Deleted relationship: " + buildingFloorRelationshipId);
try {
client.deleteDigitalTwin(buildingTwinId);
client.deleteDigitalTwin(floorTwinId);
}
catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to delete digital twin due to" + ex);
}
try {
client.deleteModel(sampleBuildingModelId);
client.deleteModel(sampleFloorModelId);
}
catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to delete models due to" + ex);
}
} | class RelationshipsSyncSamples {
private static DigitalTwinsClient client;
private static final ObjectMapper mapper = new ObjectMapper();
public static Function<Integer, String> randomIntegerStringGenerator = (maxLength) -> {
int randInt = new Random().nextInt((int)Math.pow(10, 8) - 1) + 1;
return String.valueOf(randInt);
};
public static void main(String[] args) throws IOException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runRelationshipsSample();
}
@SuppressWarnings("rawtypes")
} | class RelationshipsSyncSamples {
private static DigitalTwinsClient client;
private static final ObjectMapper mapper = new ObjectMapper();
public static Function<Integer, String> randomIntegerStringGenerator = (maxLength) -> {
int randInt = new Random().nextInt((int)Math.pow(10, 8) - 1) + 1;
return String.valueOf(randInt);
};
public static void main(String[] args) throws IOException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runRelationshipsSample();
}
} |
Is the move to do-while for readability? | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | } while (--channelsAvailable> 0); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
nit: (style) space before > | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | } while (--channelsAvailable> 0); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Is this same as above ensureInEventLoop? | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | this.ensureInEventLoop(); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Its very easy to slip stream changes violating the assumptions. We need a mechanism to guard/detect (in order of preference) for these critical aspects. How about fail in our gates/CTL/perf runs at-least? How about doing all our current validations with fail semantics? | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | this.ensureInEventLoop(); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
its error trace and I am not seeing them at-least in my runs. --- In reply to: [487800413](https://github.com/Azure/azure-sdk-for-java/pull/15157#discussion_r487800413) [](ancestors = 487800413) | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | this.ensureInEventLoop(); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Clarification(non-blocking): Any idea if netty duplex channel support timeout OOB? | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirator.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | requestExpirator.execute(record::expire); | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirationExecutor.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirator = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} |
RntbdClientChannelPool is a ChannelPool. So far my understanding is its an abstraction facilitating the pooling mechanism. Haven't seen it coupled with the core netty Channels or handlers. The attribute is a way of correlating it with the pool. Below mechanism is to purely ensure that release done on the same pool. else case is interesting. Closing on this channel will only release the underlying channel but the associated pool state will be in-consistent. Mi-targeting can happen if there are multiple ServcieEndpints for the same remote address, which means idle-time handling. Lets not gate these fixes on it. Please remove this comment. | private void releaseChannel(final Channel channel, final Promise<Void> promise) {
checkState(channel.eventLoop().inEventLoop());
final ChannelPool pool = channel.attr(POOL_KEY).getAndSet(null);
final boolean acquired = this.acquiredChannels.get(channel) != null;
if (acquired && pool == this) {
try {
if (this.releaseHealthCheck) {
this.doChannelHealthCheckOnRelease(channel, promise);
} else {
if (this.executor.inEventLoop()) {
this.releaseAndOfferChannel(channel, promise);
} else {
this.executor.submit(() -> this.releaseAndOfferChannel(channel, promise));
}
}
} catch (Throwable cause) {
if (this.executor.inEventLoop()) {
this.closeChannelAndFail(channel, cause, promise);
} else {
this.executor.submit(() -> this.closeChannelAndFail(channel, cause, promise));
}
}
} else {
final IllegalStateException error = new IllegalStateException(lenientFormat(
"%s cannot be released because it was not acquired by this pool: %s",
RntbdObjectMapper.toJson(channel),
this));
if (this.executor.inEventLoop()) {
this.closeChannelAndFail(channel, error, promise);
} else {
this.executor.submit(() -> this.closeChannelAndFail(channel, error, promise));
}
}
} | private void releaseChannel(final Channel channel, final Promise<Void> promise) {
checkState(channel.eventLoop().inEventLoop());
final ChannelPool pool = channel.attr(POOL_KEY).getAndSet(null);
final boolean acquired = this.acquiredChannels.get(channel) != null;
if (acquired && pool == this) {
try {
if (this.releaseHealthCheck) {
this.doChannelHealthCheckOnRelease(channel, promise);
} else {
if (this.executor.inEventLoop()) {
this.releaseAndOfferChannel(channel, promise);
} else {
this.executor.submit(() -> this.releaseAndOfferChannel(channel, promise));
}
}
} catch (Throwable cause) {
if (this.executor.inEventLoop()) {
this.closeChannelAndFail(channel, cause, promise);
} else {
this.executor.submit(() -> this.closeChannelAndFail(channel, cause, promise));
}
}
} else {
final IllegalStateException error = new IllegalStateException(lenientFormat(
"%s cannot be released because it was not acquired by this pool: %s",
RntbdObjectMapper.toJson(channel),
this));
if (this.executor.inEventLoop()) {
this.closeChannelAndFail(channel, error, promise);
} else {
this.executor.submit(() -> this.closeChannelAndFail(channel, error, promise));
}
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | |
Did it help in any scenario or is it a defensive programming? | private void releaseAndOfferChannel(final Channel channel, final Promise<Void> promise) {
this.ensureInEventLoop();
try {
this.acquiredChannels.remove(channel);
if (this.offerChannel(channel)) {
this.poolHandler.channelReleased(channel);
promise.setSuccess(null);
} else {
final IllegalStateException error = new StacklessIllegalStateException(lenientFormat(
"cannot offer channel back to pool because the pool is at capacity (%s)\n %s\n %s",
this.maxChannels,
this,
channel));
this.closeChannelAndFail(channel, error, promise);
}
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
}
} | this.acquiredChannels.remove(channel); | private void releaseAndOfferChannel(final Channel channel, final Promise<Void> promise) {
this.ensureInEventLoop();
try {
if (this.acquiredChannels.remove(channel) == null) {
logger.warn(
"Unexpected race condition - releaseChannel called twice for the same channel [{} -> {}]",
channel.id(),
this.remoteAddress());
promise.setSuccess(null);
return;
}
if (this.offerChannel(channel)) {
this.poolHandler.channelReleased(channel);
promise.setSuccess(null);
} else {
final IllegalStateException error = new StacklessIllegalStateException(lenientFormat(
"cannot offer channel back to pool because the pool is at capacity (%s)\n %s\n %s",
this.maxChannels,
this,
channel));
this.closeChannelAndFail(channel, error, promise);
}
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Please add comments on reason for "false' choice. | private Channel pollChannel() {
ensureInEventLoop();
final Channel first = this.availableChannels.pollLast();
if (first == null) {
return null;
}
if (this.isClosed()) {
return first;
}
if (this.isChannelServiceable(first, false)) {
return first;
}
this.availableChannels.offer(first);
for (Channel next = this.availableChannels.pollLast(); next != first; next = this.availableChannels.pollLast()) {
assert next != null : "impossible";
if (next.isActive()) {
if (this.isChannelServiceable(next, false)) {
return next;
}
this.availableChannels.offer(next);
}
}
this.availableChannels.offer(first);
return null;
} | if (this.isChannelServiceable(first, false)) { | private Channel pollChannel() {
ensureInEventLoop();
final Channel first = this.availableChannels.pollLast();
if (first == null) {
return null;
}
if (this.isClosed()) {
return first;
}
if (this.isChannelServiceable(first, false)) {
return first;
}
this.availableChannels.offer(first);
for (Channel next = this.availableChannels.pollLast(); next != first; next = this.availableChannels.pollLast()) {
assert next != null : "impossible";
if (next.isActive()) {
if (this.isChannelServiceable(next, false)) {
return next;
}
this.availableChannels.offer(next);
}
}
this.availableChannels.offer(first);
return null;
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Clarification: Any idea on why the first channel short circuit has a different pre-condition (isClosed())? Or why can't it be a simple loop and pick the one which is available? | private Channel pollChannel() {
ensureInEventLoop();
final Channel first = this.availableChannels.pollLast();
if (first == null) {
return null;
}
if (this.isClosed()) {
return first;
}
if (this.isChannelServiceable(first, false)) {
return first;
}
this.availableChannels.offer(first);
for (Channel next = this.availableChannels.pollLast(); next != first; next = this.availableChannels.pollLast()) {
assert next != null : "impossible";
if (next.isActive()) {
if (this.isChannelServiceable(next, false)) {
return next;
}
this.availableChannels.offer(next);
}
}
this.availableChannels.offer(first);
return null;
} | if (next.isActive()) { | private Channel pollChannel() {
ensureInEventLoop();
final Channel first = this.availableChannels.pollLast();
if (first == null) {
return null;
}
if (this.isClosed()) {
return first;
}
if (this.isChannelServiceable(first, false)) {
return first;
}
this.availableChannels.offer(first);
for (Channel next = this.availableChannels.pollLast(); next != first; next = this.availableChannels.pollLast()) {
assert next != null : "impossible";
if (next.isActive()) {
if (this.isChannelServiceable(next, false)) {
return next;
}
this.availableChannels.offer(next);
}
}
this.availableChannels.offer(first);
return null;
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
ACK - but I think we all agree that making the changes to fail fast will result in additional risk and need for validation (probably with changes to test infrastructure) - so IMO this is something we should do after releasing the hot fix. Makes sense? | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | this.ensureInEventLoop(); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Agreed. Removed the TODO. | private void releaseChannel(final Channel channel, final Promise<Void> promise) {
checkState(channel.eventLoop().inEventLoop());
final ChannelPool pool = channel.attr(POOL_KEY).getAndSet(null);
final boolean acquired = this.acquiredChannels.get(channel) != null;
if (acquired && pool == this) {
try {
if (this.releaseHealthCheck) {
this.doChannelHealthCheckOnRelease(channel, promise);
} else {
if (this.executor.inEventLoop()) {
this.releaseAndOfferChannel(channel, promise);
} else {
this.executor.submit(() -> this.releaseAndOfferChannel(channel, promise));
}
}
} catch (Throwable cause) {
if (this.executor.inEventLoop()) {
this.closeChannelAndFail(channel, cause, promise);
} else {
this.executor.submit(() -> this.closeChannelAndFail(channel, cause, promise));
}
}
} else {
final IllegalStateException error = new IllegalStateException(lenientFormat(
"%s cannot be released because it was not acquired by this pool: %s",
RntbdObjectMapper.toJson(channel),
this));
if (this.executor.inEventLoop()) {
this.closeChannelAndFail(channel, error, promise);
} else {
this.executor.submit(() -> this.closeChannelAndFail(channel, error, promise));
}
}
} | private void releaseChannel(final Channel channel, final Promise<Void> promise) {
checkState(channel.eventLoop().inEventLoop());
final ChannelPool pool = channel.attr(POOL_KEY).getAndSet(null);
final boolean acquired = this.acquiredChannels.get(channel) != null;
if (acquired && pool == this) {
try {
if (this.releaseHealthCheck) {
this.doChannelHealthCheckOnRelease(channel, promise);
} else {
if (this.executor.inEventLoop()) {
this.releaseAndOfferChannel(channel, promise);
} else {
this.executor.submit(() -> this.releaseAndOfferChannel(channel, promise));
}
}
} catch (Throwable cause) {
if (this.executor.inEventLoop()) {
this.closeChannelAndFail(channel, cause, promise);
} else {
this.executor.submit(() -> this.closeChannelAndFail(channel, cause, promise));
}
}
} else {
final IllegalStateException error = new IllegalStateException(lenientFormat(
"%s cannot be released because it was not acquired by this pool: %s",
RntbdObjectMapper.toJson(channel),
this));
if (this.executor.inEventLoop()) {
this.closeChannelAndFail(channel, error, promise);
} else {
this.executor.submit(() -> this.closeChannelAndFail(channel, error, promise));
}
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | |
Added comments | private Channel pollChannel() {
ensureInEventLoop();
final Channel first = this.availableChannels.pollLast();
if (first == null) {
return null;
}
if (this.isClosed()) {
return first;
}
if (this.isChannelServiceable(first, false)) {
return first;
}
this.availableChannels.offer(first);
for (Channel next = this.availableChannels.pollLast(); next != first; next = this.availableChannels.pollLast()) {
assert next != null : "impossible";
if (next.isActive()) {
if (this.isChannelServiceable(next, false)) {
return next;
}
this.availableChannels.offer(next);
}
}
this.availableChannels.offer(first);
return null;
} | if (this.isChannelServiceable(first, false)) { | private Channel pollChannel() {
ensureInEventLoop();
final Channel first = this.availableChannels.pollLast();
if (first == null) {
return null;
}
if (this.isClosed()) {
return first;
}
if (this.isChannelServiceable(first, false)) {
return first;
}
this.availableChannels.offer(first);
for (Channel next = this.availableChannels.pollLast(); next != first; next = this.availableChannels.pollLast()) {
assert next != null : "impossible";
if (next.isActive()) {
if (this.isChannelServiceable(next, false)) {
return next;
}
this.availableChannels.offer(next);
}
}
this.availableChannels.offer(first);
return null;
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
nit: too much happening in this 1 statement - add, new & null checks. Breaking it down probably makes it easier to read. | public JsonPatchDocument appendCopy(String from, String path) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.COPY,
Objects.requireNonNull(path, "'path' cannot be null."),
Objects.requireNonNull(from, "'from' cannot be null."), null));
return this;
} | Objects.requireNonNull(from, "'from' cannot be null."), null)); | public JsonPatchDocument appendCopy(String from, String path) {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(path, "'path' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.COPY, path, from, null));
return this;
} | class JsonPatchDocument {
private static final ObjectMapper MAPPER = ((JacksonAdapter) JacksonAdapter.createDefaultSerializerAdapter())
.serializer();
private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class);
private final List<JsonPatchOperation> operations;
/**
* Creates a new JSON Patch document.
*/
public JsonPatchDocument() {
this.operations = new ArrayList<>();
}
/**
* Appends an "add" operation to this JSON Patch document.
* <p>
* If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the
* previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendAdd
*
* @param path The path to apply the addition.
* @param rawJsonValue The raw JSON value to add to the path.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendAdd(String path, String rawJsonValue) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.ADD,
Objects.requireNonNull(path, "'path' cannot be null."), null,
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.")));
return this;
}
/**
* Appends a "replace" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendReplace
*
* @param path The path to replace.
* @param rawJsonValue The raw JSON value to use as the replacement.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendReplace(String path, String rawJsonValue) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.REPLACE,
Objects.requireNonNull(path, "'path' cannot be null."), null,
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.")));
return this;
}
/**
* Appends a "copy" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendCopy
*
* @param from The path to copy from.
* @param path The path to copy to.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code from} or {@code path} is null.
*/
/**
* Appends a "move" operation to this JSON Patch document.
* <p>
* For the operation to be successful {@code path} cannot be a child node of {@code from}.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendMove
*
* @param from The path to move from.
* @param path The path to move to.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code from} or {@code path} is null.
*/
public JsonPatchDocument appendMove(String from, String path) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.MOVE,
Objects.requireNonNull(path, "'path' cannot be null."),
Objects.requireNonNull(from, "'from' cannot be null."), null));
return this;
}
/**
* Appends a "remove" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendRemove
*
* @param path The path to remove.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} is null.
*/
public JsonPatchDocument appendRemove(String path) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.REMOVE,
Objects.requireNonNull(path, "'path' cannot be null."), null, null));
return this;
}
/**
* Appends a "test" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendTest
*
* @param path The path to test.
* @param rawJsonValue The raw JSON value to test against.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendTest(String path, String rawJsonValue) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.TEST,
Objects.requireNonNull(path, "'path' cannot be null."), null,
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.")));
return this;
}
/**
* Gets a formatted JSON string representation of this JSON Patch document.
*
* @return The formatted JSON String representing this JSON Patch docuemnt.
*/
@Override
public String toString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
JsonGenerator generator = MAPPER.createGenerator(outputStream);
generator.writeStartArray();
for (JsonPatchOperation operation : operations) {
writeOperation(generator, operation);
}
generator.writeEndArray();
generator.flush();
generator.close();
return outputStream.toString("UTF-8");
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private static void writeOperation(JsonGenerator generator, JsonPatchOperation operation) throws IOException {
generator.writeStartObject();
generator.writeStringField("op", operation.getKind().toString());
if (operation.getFrom() != null) {
generator.writeStringField("from", operation.getFrom());
}
generator.writeStringField("path", operation.getPath());
if (operation.getRawJsonValue() != null) {
generator.writeFieldName("value");
generator.writeTree(MAPPER.readTree(operation.getRawJsonValue()));
}
generator.writeEndObject();
}
} | class JsonPatchDocument {
private static final ObjectMapper MAPPER = ((JacksonAdapter) JacksonAdapter.createDefaultSerializerAdapter())
.serializer();
private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class);
private final List<JsonPatchOperation> operations;
/**
* Creates a new JSON Patch document.
*/
public JsonPatchDocument() {
this.operations = new ArrayList<>();
}
/**
* Appends an "add" operation to this JSON Patch document.
* <p>
* If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the
* previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendAdd
*
* @param path The path to apply the addition.
* @param rawJsonValue The raw JSON value to add to the path.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendAdd(String path, String rawJsonValue) {
Objects.requireNonNull(path, "'path' cannot be null.");
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.ADD, path, null, rawJsonValue));
return this;
}
/**
* Appends a "replace" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendReplace
*
* @param path The path to replace.
* @param rawJsonValue The raw JSON value to use as the replacement.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendReplace(String path, String rawJsonValue) {
Objects.requireNonNull(path, "'path' cannot be null.");
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.REPLACE, path, null, rawJsonValue));
return this;
}
/**
* Appends a "copy" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendCopy
*
* @param from The path to copy from.
* @param path The path to copy to.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code from} or {@code path} is null.
*/
/**
* Appends a "move" operation to this JSON Patch document.
* <p>
* For the operation to be successful {@code path} cannot be a child node of {@code from}.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendMove
*
* @param from The path to move from.
* @param path The path to move to.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code from} or {@code path} is null.
*/
public JsonPatchDocument appendMove(String from, String path) {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(path, "'path' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.MOVE, path, from, null));
return this;
}
/**
* Appends a "remove" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendRemove
*
* @param path The path to remove.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} is null.
*/
public JsonPatchDocument appendRemove(String path) {
Objects.requireNonNull(path, "'path' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.REMOVE, path, null, null));
return this;
}
/**
* Appends a "test" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendTest
*
* @param path The path to test.
* @param rawJsonValue The raw JSON value to test against.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendTest(String path, String rawJsonValue) {
Objects.requireNonNull(path, "'path' cannot be null.");
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.TEST, path, null, rawJsonValue));
return this;
}
/**
* Gets a formatted JSON string representation of this JSON Patch document.
*
* @return The formatted JSON String representing this JSON Patch docuemnt.
*/
@Override
public String toString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
JsonGenerator generator = MAPPER.createGenerator(outputStream);
generator.writeStartArray();
for (JsonPatchOperation operation : operations) {
writeOperation(generator, operation);
}
generator.writeEndArray();
generator.flush();
generator.close();
return outputStream.toString("UTF-8");
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private static void writeOperation(JsonGenerator generator, JsonPatchOperation operation) throws IOException {
generator.writeStartObject();
generator.writeStringField("op", operation.getKind().toString());
if (operation.getFrom() != null) {
generator.writeStringField("from", operation.getFrom());
}
generator.writeStringField("path", operation.getPath());
if (operation.getRawJsonValue() != null) {
generator.writeFieldName("value");
generator.writeTree(MAPPER.readTree(operation.getRawJsonValue()));
}
generator.writeEndObject();
}
} |
The is a comment in the short-circuit above already - to avoid an infinite loop in the close code sequence. | private Channel pollChannel() {
ensureInEventLoop();
final Channel first = this.availableChannels.pollLast();
if (first == null) {
return null;
}
if (this.isClosed()) {
return first;
}
if (this.isChannelServiceable(first, false)) {
return first;
}
this.availableChannels.offer(first);
for (Channel next = this.availableChannels.pollLast(); next != first; next = this.availableChannels.pollLast()) {
assert next != null : "impossible";
if (next.isActive()) {
if (this.isChannelServiceable(next, false)) {
return next;
}
this.availableChannels.offer(next);
}
}
this.availableChannels.offer(first);
return null;
} | if (next.isActive()) { | private Channel pollChannel() {
ensureInEventLoop();
final Channel first = this.availableChannels.pollLast();
if (first == null) {
return null;
}
if (this.isClosed()) {
return first;
}
if (this.isChannelServiceable(first, false)) {
return first;
}
this.availableChannels.offer(first);
for (Channel next = this.availableChannels.pollLast(); next != first; next = this.availableChannels.pollLast()) {
assert next != null : "impossible";
if (next.isActive()) {
if (this.isChannelServiceable(next, false)) {
return next;
}
this.availableChannels.offer(next);
}
}
this.availableChannels.offer(first);
return null;
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
+1 to this pattern. earlier might look okey as poolHandler notification is very light weight and almost doesn't fail, but this is a pattern we should force in reviews. Thanks, | private void notifyChannelConnect(final ChannelFuture future, final Promise<Channel> promise) {
ensureInEventLoop();
reportIssueUnless(logger, this.connecting.get(), this, "connecting: false");
try {
if (future.isSuccess()) {
final Channel channel = future.channel();
try {
this.poolHandler.channelAcquired(channel);
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
return;
}
if (promise.trySuccess(channel)) {
if (logger.isDebugEnabled()) {
logger.debug("established a channel local {}, remote {}", channel.localAddress(), channel.remoteAddress());
}
this.acquiredChannels.compute(channel, (ignored, acquiredChannel) -> {
reportIssueUnless(logger, acquiredChannel == null, this,
"Channel({}) to be acquired has already been acquired",
channel);
reportIssueUnless(logger, !this.availableChannels.remove(channel), this,
"Channel({}) to be acquired is still in the list of available channels",
channel);
return channel;
});
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect promise.trySuccess(channel)=false");
}
this.closeChannel(channel);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect future was not successful");
}
promise.tryFailure(future.cause());
}
} finally {
this.connecting.set(false);
}
} | this.connecting.set(false); | private void notifyChannelConnect(final ChannelFuture future, final Promise<Channel> promise) {
ensureInEventLoop();
reportIssueUnless(logger, this.connecting.get(), this, "connecting: false");
try {
if (future.isSuccess()) {
final Channel channel = future.channel();
try {
this.poolHandler.channelAcquired(channel);
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
return;
}
if (promise.trySuccess(channel)) {
if (logger.isDebugEnabled()) {
logger.debug("established a channel local {}, remote {}", channel.localAddress(), channel.remoteAddress());
}
this.acquiredChannels.compute(channel, (ignored, acquiredChannel) -> {
reportIssueUnless(logger, acquiredChannel == null, this,
"Channel({}) to be acquired has already been acquired",
channel);
reportIssueUnless(logger, !this.availableChannels.remove(channel), this,
"Channel({}) to be acquired is still in the list of available channels",
channel);
return channel;
});
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect promise.trySuccess(channel)=false");
}
this.closeChannel(channel);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect future was not successful");
}
promise.tryFailure(future.cause());
}
} finally {
this.connecting.set(false);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
nit: new line before. | private void notifyChannelConnect(final ChannelFuture future, final Promise<Channel> promise) {
ensureInEventLoop();
reportIssueUnless(logger, this.connecting.get(), this, "connecting: false");
try {
if (future.isSuccess()) {
final Channel channel = future.channel();
try {
this.poolHandler.channelAcquired(channel);
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
return;
}
if (promise.trySuccess(channel)) {
if (logger.isDebugEnabled()) {
logger.debug("established a channel local {}, remote {}", channel.localAddress(), channel.remoteAddress());
}
this.acquiredChannels.compute(channel, (ignored, acquiredChannel) -> {
reportIssueUnless(logger, acquiredChannel == null, this,
"Channel({}) to be acquired has already been acquired",
channel);
reportIssueUnless(logger, !this.availableChannels.remove(channel), this,
"Channel({}) to be acquired is still in the list of available channels",
channel);
return channel;
});
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect promise.trySuccess(channel)=false");
}
this.closeChannel(channel);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect future was not successful");
}
promise.tryFailure(future.cause());
}
} finally {
this.connecting.set(false);
}
} | this.acquiredChannels.compute(channel, (ignored, acquiredChannel) -> { | private void notifyChannelConnect(final ChannelFuture future, final Promise<Channel> promise) {
ensureInEventLoop();
reportIssueUnless(logger, this.connecting.get(), this, "connecting: false");
try {
if (future.isSuccess()) {
final Channel channel = future.channel();
try {
this.poolHandler.channelAcquired(channel);
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
return;
}
if (promise.trySuccess(channel)) {
if (logger.isDebugEnabled()) {
logger.debug("established a channel local {}, remote {}", channel.localAddress(), channel.remoteAddress());
}
this.acquiredChannels.compute(channel, (ignored, acquiredChannel) -> {
reportIssueUnless(logger, acquiredChannel == null, this,
"Channel({}) to be acquired has already been acquired",
channel);
reportIssueUnless(logger, !this.availableChannels.remove(channel), this,
"Channel({}) to be acquired is still in the list of available channels",
channel);
return channel;
});
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect promise.trySuccess(channel)=false");
}
this.closeChannel(channel);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect future was not successful");
}
promise.tryFailure(future.cause());
}
} finally {
this.connecting.set(false);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Fixed | private void notifyChannelConnect(final ChannelFuture future, final Promise<Channel> promise) {
ensureInEventLoop();
reportIssueUnless(logger, this.connecting.get(), this, "connecting: false");
try {
if (future.isSuccess()) {
final Channel channel = future.channel();
try {
this.poolHandler.channelAcquired(channel);
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
return;
}
if (promise.trySuccess(channel)) {
if (logger.isDebugEnabled()) {
logger.debug("established a channel local {}, remote {}", channel.localAddress(), channel.remoteAddress());
}
this.acquiredChannels.compute(channel, (ignored, acquiredChannel) -> {
reportIssueUnless(logger, acquiredChannel == null, this,
"Channel({}) to be acquired has already been acquired",
channel);
reportIssueUnless(logger, !this.availableChannels.remove(channel), this,
"Channel({}) to be acquired is still in the list of available channels",
channel);
return channel;
});
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect promise.trySuccess(channel)=false");
}
this.closeChannel(channel);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect future was not successful");
}
promise.tryFailure(future.cause());
}
} finally {
this.connecting.set(false);
}
} | this.acquiredChannels.compute(channel, (ignored, acquiredChannel) -> { | private void notifyChannelConnect(final ChannelFuture future, final Promise<Channel> promise) {
ensureInEventLoop();
reportIssueUnless(logger, this.connecting.get(), this, "connecting: false");
try {
if (future.isSuccess()) {
final Channel channel = future.channel();
try {
this.poolHandler.channelAcquired(channel);
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
return;
}
if (promise.trySuccess(channel)) {
if (logger.isDebugEnabled()) {
logger.debug("established a channel local {}, remote {}", channel.localAddress(), channel.remoteAddress());
}
this.acquiredChannels.compute(channel, (ignored, acquiredChannel) -> {
reportIssueUnless(logger, acquiredChannel == null, this,
"Channel({}) to be acquired has already been acquired",
channel);
reportIssueUnless(logger, !this.availableChannels.remove(channel), this,
"Channel({}) to be acquired is still in the list of available channels",
channel);
return channel;
});
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect promise.trySuccess(channel)=false");
}
this.closeChannel(channel);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("notifyChannelConnect future was not successful");
}
promise.tryFailure(future.cause());
}
} finally {
this.connecting.set(false);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Yes - removed the comment. There was one scenario where we ended up leaving a channel in acquiredChannels and availableChannels. This was part of the fix to make sure we don't establish more connections than MaxChannels... | private void releaseAndOfferChannel(final Channel channel, final Promise<Void> promise) {
this.ensureInEventLoop();
try {
this.acquiredChannels.remove(channel);
if (this.offerChannel(channel)) {
this.poolHandler.channelReleased(channel);
promise.setSuccess(null);
} else {
final IllegalStateException error = new StacklessIllegalStateException(lenientFormat(
"cannot offer channel back to pool because the pool is at capacity (%s)\n %s\n %s",
this.maxChannels,
this,
channel));
this.closeChannelAndFail(channel, error, promise);
}
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
}
} | this.acquiredChannels.remove(channel); | private void releaseAndOfferChannel(final Channel channel, final Promise<Void> promise) {
this.ensureInEventLoop();
try {
if (this.acquiredChannels.remove(channel) == null) {
logger.warn(
"Unexpected race condition - releaseChannel called twice for the same channel [{} -> {}]",
channel.id(),
this.remoteAddress());
promise.setSuccess(null);
return;
}
if (this.offerChannel(channel)) {
this.poolHandler.channelReleased(channel);
promise.setSuccess(null);
} else {
final IllegalStateException error = new StacklessIllegalStateException(lenientFormat(
"cannot offer channel back to pool because the pool is at capacity (%s)\n %s\n %s",
this.maxChannels,
this,
channel));
this.closeChannelAndFail(channel, error, promise);
}
} catch (Throwable error) {
this.closeChannelAndFail(channel, error, promise);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Can be discussed offline. | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirator.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | requestExpirator.execute(record::expire); | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirationExecutor.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirator = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} |
ACK - but let's please track this in work items - not in this PR. We need to make progress on this PR quickly to ship the hotfix. | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirator.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | requestExpirator.execute(record::expire); | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirationExecutor.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirator = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} |
No - it is intentionally executing at least once (even if no channels available to allow for more eager connection initiation. Worst case we pull one pendingAcquisition task from the head and re-enqueue it at the tail. Can result in some unfairness - but from test tests we ran and the discussions/analysis in the last couple of days that trade-off is reasonable. Mo's comment above explains the possible unfairness - so I think we are good here? | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | } while (--channelsAvailable> 0); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Correct | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirator.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) {
return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> {
reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record);
final Timeout pendingRequestTimeout = record.newTimeout(timeout -> {
requestExpirationExecutor.execute(record::expire);
});
record.whenComplete((response, error) -> {
this.pendingRequests.remove(id);
pendingRequestTimeout.cancel();
});
return record;
});
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirator = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} | class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler {
private static final ClosedChannelException ON_CHANNEL_UNREGISTERED =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered");
private static final ClosedChannelException ON_CLOSE =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close");
private static final ClosedChannelException ON_DEREGISTER =
ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister");
private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory(
"request-expirator",
true,
Thread.NORM_PRIORITY));
private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class);
private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>();
private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>();
private final ChannelHealthChecker healthChecker;
private final int pendingRequestLimit;
private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests;
private final Timestamps timestamps = new Timestamps();
private boolean closingExceptionally = false;
private CoalescingBufferQueue pendingWrites;
public RntbdRequestManager(final ChannelHealthChecker healthChecker, final int pendingRequestLimit) {
checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit);
checkNotNull(healthChecker, "healthChecker");
this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit);
this.pendingRequestLimit = pendingRequestLimit;
this.healthChecker = healthChecker;
}
/**
* Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerAdded(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerAdded");
}
/**
* Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
* anymore.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void handlerRemoved(final ChannelHandlerContext context) {
this.traceOperation(context, "handlerRemoved");
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} is now active
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelActive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelActive");
context.fireChannelActive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime
* <p>
* This method will only be called after the channel is closed.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelInactive(final ChannelHandlerContext context) {
this.traceOperation(context, "channelInactive");
context.fireChannelInactive();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs.
* @param message The message read.
*/
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) {
this.traceOperation(context, "channelRead");
try {
if (message.getClass() == RntbdResponse.class) {
try {
this.messageReceived(context, (RntbdResponse) message);
} catch (CorruptedFrameException error) {
this.exceptionCaught(context, error);
} catch (Throwable throwable) {
reportIssue(context, "{} ", message, throwable);
this.exceptionCaught(context, throwable);
}
} else {
final IllegalStateException error = new IllegalStateException(
lenientFormat("expected message of %s, not %s: %s",
RntbdResponse.class,
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
} finally {
if (message instanceof ReferenceCounted) {
boolean released = ((ReferenceCounted) message).release();
reportIssueUnless(released, context, "failed to release message: {}", message);
}
}
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read.
* <p>
* If {@link ChannelOption
* {@link Channel} will be made until {@link ChannelHandlerContext
* for outbound messages to be written.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelReadComplete(final ChannelHandlerContext context) {
this.traceOperation(context, "channelReadComplete");
this.timestamps.channelReadCompleted();
context.fireChannelReadComplete();
}
/**
* Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest}
* <p>
* This method then calls {@link ChannelHandlerContext
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
*/
@Override
public void channelRegistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelRegistered");
reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites);
this.pendingWrites = new CoalescingBufferQueue(context.channel());
context.fireChannelRegistered();
}
/**
* The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop}
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelUnregistered(final ChannelHandlerContext context) {
this.traceOperation(context, "channelUnregistered");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED);
} else {
logger.debug("{} channelUnregistered exceptionally", context);
}
context.fireChannelUnregistered();
}
/**
* Gets called once the writable state of a {@link Channel} changed. You can check the state with
* {@link Channel
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
*/
@Override
public void channelWritabilityChanged(final ChannelHandlerContext context) {
this.traceOperation(context, "channelWritabilityChanged");
context.fireChannelWritabilityChanged();
}
/**
* Processes {@link ChannelHandlerContext
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param cause Exception caught
*/
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) {
this.traceOperation(context, "exceptionCaught", cause);
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, cause);
logger.debug("{} closing due to:", context, cause);
context.flush().close();
}
}
/**
* Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline
* <p>
* All but inbound request management events are ignored.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs
* @param event An object representing a user event
*/
@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) {
this.traceOperation(context, "userEventTriggered", event);
try {
if (event instanceof IdleStateEvent) {
this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> {
final Throwable cause;
if (future.isSuccess()) {
if (future.get()) {
return;
}
cause = UnhealthyChannelException.INSTANCE;
} else {
cause = future.cause();
}
this.exceptionCaught(context, cause);
});
return;
}
if (event instanceof RntbdContext) {
this.contextFuture.complete((RntbdContext) event);
this.removeContextNegotiatorAndFlushPendingWrites(context);
return;
}
if (event instanceof RntbdContextException) {
this.contextFuture.completeExceptionally((RntbdContextException) event);
context.pipeline().flush().close();
return;
}
context.fireUserEventTriggered(event);
} catch (Throwable error) {
reportIssue(context, "{}: ", event, error);
this.exceptionCaught(context, error);
}
}
/**
* Called once a bind operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the bind operation is made
* @param localAddress the {@link SocketAddress} to which it should bound
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) {
this.traceOperation(context, "bind", localAddress);
context.bind(localAddress, promise);
}
/**
* Called once a close operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the close operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "close");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
} else {
logger.debug("{} closed exceptionally", context);
}
final SslHandler sslHandler = context.pipeline().get(SslHandler.class);
if (sslHandler != null) {
sslHandler.closeOutbound();
}
context.close(promise);
}
/**
* Called once a connect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the connect operation is made
* @param remoteAddress the {@link SocketAddress} to which it should connect
* @param localAddress the {@link SocketAddress} which is used as source on connect
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void connect(
final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress,
final ChannelPromise promise
) {
this.traceOperation(context, "connect", remoteAddress, localAddress);
context.connect(remoteAddress, localAddress, promise);
}
/**
* Called once a deregister operation is made from the current registered {@link EventLoop}.
*
* @param context the {@link ChannelHandlerContext} for which the deregister operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "deregister");
if (!this.closingExceptionally) {
this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER);
} else {
logger.debug("{} deregistered exceptionally", context);
}
context.deregister(promise);
}
/**
* Called once a disconnect operation is made.
*
* @param context the {@link ChannelHandlerContext} for which the disconnect operation is made
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) {
this.traceOperation(context, "disconnect");
context.disconnect(promise);
}
/**
* Called once a flush operation is made
* <p>
* The flush operation will try to flush out all previous written messages that are pending.
*
* @param context the {@link ChannelHandlerContext} for which the flush operation is made
*/
@Override
public void flush(final ChannelHandlerContext context) {
this.traceOperation(context, "flush");
context.flush();
}
/**
* Intercepts {@link ChannelHandlerContext
*
* @param context the {@link ChannelHandlerContext} for which the read operation is made
*/
@Override
public void read(final ChannelHandlerContext context) {
this.traceOperation(context, "read");
context.read();
}
/**
* Called once a write operation is made
* <p>
* The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed
* to the actual {@link Channel}. This will occur when {@link Channel
*
* @param context the {@link ChannelHandlerContext} for which the write operation is made
* @param message the message to write
* @param promise the {@link ChannelPromise} to notify once the operation completes
*/
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
this.traceOperation(context, "write", message);
if (message.getClass() == RntbdRequestRecord.class) {
final RntbdRequestRecord record = (RntbdRequestRecord) message;
this.timestamps.channelWriteAttempted();
context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> {
record.stage(RntbdRequestRecord.Stage.SENT);
if (completed.isSuccess()) {
this.timestamps.channelWriteCompleted();
}
});
return;
}
if (message == RntbdHealthCheckRequest.MESSAGE) {
context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> {
if (completed.isSuccess()) {
this.timestamps.channelPingCompleted();
}
});
return;
}
final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s",
message.getClass(),
message));
reportIssue(context, "", error);
this.exceptionCaught(context, error);
}
int pendingRequestCount() {
return this.pendingRequests.size();
}
Optional<RntbdContext> rntbdContext() {
return Optional.of(this.contextFuture.getNow(null));
}
CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() {
return this.contextRequestFuture;
}
boolean hasRequestedRntbdContext() {
return this.contextRequestFuture.getNow(null) != null;
}
boolean hasRntbdContext() {
return this.contextFuture.getNow(null) != null;
}
boolean isServiceable(final int demand, boolean ignoreMaxRequestPerChannel) {
reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued");
final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand);
return ignoreMaxRequestPerChannel || this.pendingRequests.size() < limit;
}
void pendWrite(final ByteBuf out, final ChannelPromise promise) {
this.pendingWrites.add(out, promise);
}
Timestamps snapshotTimestamps() {
return new Timestamps(this.timestamps);
}
private void completeAllPendingRequestsExceptionally(
final ChannelHandlerContext context, final Throwable throwable
) {
reportIssueUnless(!this.closingExceptionally, context, "", throwable);
this.closingExceptionally = true;
if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) {
this.pendingWrites.releaseAndFailAll(context, throwable);
}
if (this.pendingRequests.isEmpty()) {
return;
}
if (!this.contextRequestFuture.isDone()) {
this.contextRequestFuture.completeExceptionally(throwable);
}
if (!this.contextFuture.isDone()) {
this.contextFuture.completeExceptionally(throwable);
}
final int count = this.pendingRequests.size();
Exception contextRequestException = null;
String phrase = null;
if (this.contextRequestFuture.isCompletedExceptionally()) {
try {
this.contextRequestFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request write cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request write failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request write failed";
contextRequestException = new ChannelException(error);
}
} else if (this.contextFuture.isCompletedExceptionally()) {
try {
this.contextFuture.get();
} catch (final CancellationException error) {
phrase = "RNTBD context request read cancelled";
contextRequestException = error;
} catch (final Exception error) {
phrase = "RNTBD context request read failed";
contextRequestException = error;
} catch (final Throwable error) {
phrase = "RNTBD context request read failed";
contextRequestException = new ChannelException(error);
}
} else {
phrase = "closed exceptionally";
}
final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count);
final Exception cause;
if (throwable instanceof ClosedChannelException) {
cause = contextRequestException == null
? (ClosedChannelException) throwable
: contextRequestException;
} else {
cause = throwable instanceof Exception
? (Exception) throwable
: new ChannelException(throwable);
}
for (RntbdRequestRecord record : this.pendingRequests.values()) {
final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders();
final String requestUri = record.args().physicalAddress().toString();
final GoneException error = new GoneException(message, cause, (Map<String, String>) null, requestUri);
BridgeInternal.setRequestHeaders(error, requestHeaders);
record.completeExceptionally(error);
}
}
/**
* This method is called for each incoming message of type {@link RntbdResponse} to complete a request.
*
* @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs.
* @param response the {@link RntbdResponse message} received.
*/
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) {
final Long transportRequestId = response.getTransportRequestId();
if (transportRequestId == null) {
reportIssue(context, "response ignored because its transportRequestId is missing: {}", response);
return;
}
final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId);
if (requestRecord == null) {
logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response);
return;
}
requestRecord.responseLength(response.getMessageLength());
requestRecord.stage(RntbdRequestRecord.Stage.RECEIVED);
final HttpResponseStatus status = response.getStatus();
final UUID activityId = response.getActivityId();
final int statusCode = status.code();
if (HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null));
requestRecord.complete(storeResponse);
} else {
final CosmosException cause;
final long lsn = response.getHeader(RntbdResponseHeader.LSN);
final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId);
final CosmosError error = response.hasPayload()
? new CosmosError(RntbdObjectMapper.readTree(response))
: new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name());
final Map<String, String> responseHeaders = response.getHeaders().asMap(
this.rntbdContext().orElseThrow(IllegalStateException::new), activityId
);
switch (status.code()) {
case StatusCodes.BADREQUEST:
cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.CONFLICT:
cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.FORBIDDEN:
cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.GONE:
final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus));
switch (subStatusCode) {
case SubStatusCodes.COMPLETING_SPLIT:
cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.COMPLETING_PARTITION_MIGRATION:
cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.NAME_CACHE_IS_STALE:
cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case SubStatusCodes.PARTITION_KEY_RANGE_GONE:
cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
}
break;
case StatusCodes.INTERNAL_SERVER_ERROR:
cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.LOCKED:
cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.METHOD_NOT_ALLOWED:
cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.NOTFOUND:
cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.PRECONDITION_FAILED:
cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_ENTITY_TOO_LARGE:
cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.REQUEST_TIMEOUT:
cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.RETRY_WITH:
cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.SERVICE_UNAVAILABLE:
cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.TOO_MANY_REQUESTS:
cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
case StatusCodes.UNAUTHORIZED:
cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders);
break;
default:
cause = BridgeInternal.createCosmosException(status.code(), error, responseHeaders);
break;
}
requestRecord.completeExceptionally(cause);
}
}
private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) {
final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class);
negotiator.removeInboundHandler();
negotiator.removeOutboundHandler();
if (!this.pendingWrites.isEmpty()) {
this.pendingWrites.writeAndRemoveAll(context);
context.flush();
}
}
private static void reportIssue(final Object subject, final String format, final Object... args) {
RntbdReporter.reportIssue(logger, subject, format, args);
}
private static void reportIssueUnless(
final boolean predicate, final Object subject, final String format, final Object... args
) {
RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args);
}
private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) {
logger.debug("{}\n{}\n{}", operationName, context, args);
}
private static final class UnhealthyChannelException extends ChannelException {
static final UnhealthyChannelException INSTANCE = new UnhealthyChannelException();
private UnhealthyChannelException() {
super("health check failed");
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
} | |
Separated out all `Objects.requireNonNull` to their own lines. | public JsonPatchDocument appendCopy(String from, String path) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.COPY,
Objects.requireNonNull(path, "'path' cannot be null."),
Objects.requireNonNull(from, "'from' cannot be null."), null));
return this;
} | Objects.requireNonNull(from, "'from' cannot be null."), null)); | public JsonPatchDocument appendCopy(String from, String path) {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(path, "'path' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.COPY, path, from, null));
return this;
} | class JsonPatchDocument {
private static final ObjectMapper MAPPER = ((JacksonAdapter) JacksonAdapter.createDefaultSerializerAdapter())
.serializer();
private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class);
private final List<JsonPatchOperation> operations;
/**
* Creates a new JSON Patch document.
*/
public JsonPatchDocument() {
this.operations = new ArrayList<>();
}
/**
* Appends an "add" operation to this JSON Patch document.
* <p>
* If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the
* previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendAdd
*
* @param path The path to apply the addition.
* @param rawJsonValue The raw JSON value to add to the path.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendAdd(String path, String rawJsonValue) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.ADD,
Objects.requireNonNull(path, "'path' cannot be null."), null,
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.")));
return this;
}
/**
* Appends a "replace" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendReplace
*
* @param path The path to replace.
* @param rawJsonValue The raw JSON value to use as the replacement.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendReplace(String path, String rawJsonValue) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.REPLACE,
Objects.requireNonNull(path, "'path' cannot be null."), null,
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.")));
return this;
}
/**
* Appends a "copy" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendCopy
*
* @param from The path to copy from.
* @param path The path to copy to.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code from} or {@code path} is null.
*/
/**
* Appends a "move" operation to this JSON Patch document.
* <p>
* For the operation to be successful {@code path} cannot be a child node of {@code from}.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendMove
*
* @param from The path to move from.
* @param path The path to move to.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code from} or {@code path} is null.
*/
public JsonPatchDocument appendMove(String from, String path) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.MOVE,
Objects.requireNonNull(path, "'path' cannot be null."),
Objects.requireNonNull(from, "'from' cannot be null."), null));
return this;
}
/**
* Appends a "remove" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendRemove
*
* @param path The path to remove.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} is null.
*/
public JsonPatchDocument appendRemove(String path) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.REMOVE,
Objects.requireNonNull(path, "'path' cannot be null."), null, null));
return this;
}
/**
* Appends a "test" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendTest
*
* @param path The path to test.
* @param rawJsonValue The raw JSON value to test against.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendTest(String path, String rawJsonValue) {
operations.add(new JsonPatchOperation(JsonPatchOperationKind.TEST,
Objects.requireNonNull(path, "'path' cannot be null."), null,
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.")));
return this;
}
/**
* Gets a formatted JSON string representation of this JSON Patch document.
*
* @return The formatted JSON String representing this JSON Patch docuemnt.
*/
@Override
public String toString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
JsonGenerator generator = MAPPER.createGenerator(outputStream);
generator.writeStartArray();
for (JsonPatchOperation operation : operations) {
writeOperation(generator, operation);
}
generator.writeEndArray();
generator.flush();
generator.close();
return outputStream.toString("UTF-8");
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private static void writeOperation(JsonGenerator generator, JsonPatchOperation operation) throws IOException {
generator.writeStartObject();
generator.writeStringField("op", operation.getKind().toString());
if (operation.getFrom() != null) {
generator.writeStringField("from", operation.getFrom());
}
generator.writeStringField("path", operation.getPath());
if (operation.getRawJsonValue() != null) {
generator.writeFieldName("value");
generator.writeTree(MAPPER.readTree(operation.getRawJsonValue()));
}
generator.writeEndObject();
}
} | class JsonPatchDocument {
private static final ObjectMapper MAPPER = ((JacksonAdapter) JacksonAdapter.createDefaultSerializerAdapter())
.serializer();
private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class);
private final List<JsonPatchOperation> operations;
/**
* Creates a new JSON Patch document.
*/
public JsonPatchDocument() {
this.operations = new ArrayList<>();
}
/**
* Appends an "add" operation to this JSON Patch document.
* <p>
* If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the
* previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendAdd
*
* @param path The path to apply the addition.
* @param rawJsonValue The raw JSON value to add to the path.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendAdd(String path, String rawJsonValue) {
Objects.requireNonNull(path, "'path' cannot be null.");
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.ADD, path, null, rawJsonValue));
return this;
}
/**
* Appends a "replace" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendReplace
*
* @param path The path to replace.
* @param rawJsonValue The raw JSON value to use as the replacement.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendReplace(String path, String rawJsonValue) {
Objects.requireNonNull(path, "'path' cannot be null.");
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.REPLACE, path, null, rawJsonValue));
return this;
}
/**
* Appends a "copy" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendCopy
*
* @param from The path to copy from.
* @param path The path to copy to.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code from} or {@code path} is null.
*/
/**
* Appends a "move" operation to this JSON Patch document.
* <p>
* For the operation to be successful {@code path} cannot be a child node of {@code from}.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendMove
*
* @param from The path to move from.
* @param path The path to move to.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code from} or {@code path} is null.
*/
public JsonPatchDocument appendMove(String from, String path) {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(path, "'path' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.MOVE, path, from, null));
return this;
}
/**
* Appends a "remove" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendRemove
*
* @param path The path to remove.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} is null.
*/
public JsonPatchDocument appendRemove(String path) {
Objects.requireNonNull(path, "'path' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.REMOVE, path, null, null));
return this;
}
/**
* Appends a "test" operation to this JSON Patch document.
* <p>
* See <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* {@codesnippet com.azure.core.experimental.jsonpatch.JsonPatchDocument.appendTest
*
* @param path The path to test.
* @param rawJsonValue The raw JSON value to test against.
* @return The updated JsonPatchDocument object.
* @throws NullPointerException If {@code path} or {@code rawJsonValue} is null.
*/
public JsonPatchDocument appendTest(String path, String rawJsonValue) {
Objects.requireNonNull(path, "'path' cannot be null.");
Objects.requireNonNull(rawJsonValue, "'rawJsonValue' cannot be null.");
operations.add(new JsonPatchOperation(JsonPatchOperationKind.TEST, path, null, rawJsonValue));
return this;
}
/**
* Gets a formatted JSON string representation of this JSON Patch document.
*
* @return The formatted JSON String representing this JSON Patch docuemnt.
*/
@Override
public String toString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
JsonGenerator generator = MAPPER.createGenerator(outputStream);
generator.writeStartArray();
for (JsonPatchOperation operation : operations) {
writeOperation(generator, operation);
}
generator.writeEndArray();
generator.flush();
generator.close();
return outputStream.toString("UTF-8");
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
private static void writeOperation(JsonGenerator generator, JsonPatchOperation operation) throws IOException {
generator.writeStartObject();
generator.writeStringField("op", operation.getKind().toString());
if (operation.getFrom() != null) {
generator.writeStringField("from", operation.getFrom());
}
generator.writeStringField("path", operation.getPath());
if (operation.getRawJsonValue() != null) {
generator.writeFieldName("value");
generator.writeTree(MAPPER.readTree(operation.getRawJsonValue()));
}
generator.writeEndObject();
}
} |
Fixed | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | this.ensureInEventLoop(); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Fixed | private void runTasksInPendingAcquisitionQueue() {
ensureInEventLoop();
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable> 0);
} | } while (--channelsAvailable> 0); | private void runTasksInPendingAcquisitionQueue() {
this.ensureInEventLoop();
int channelsAvailable = this.availableChannels.size();
do {
final AcquireTask task = this.pendingAcquisitions.poll();
if (task == null) {
break;
}
task.acquired(true);
this.acquire(task.promise);
} while (--channelsAvailable > 0);
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireTask channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireTask task) {
task.promise.setFailure(ACQUISITION_TIMEOUT);
}
} |
not really a check but a sample code on how to check status codes ... we don't really need it for the sample to function | public static void runRelationshipsSample() throws JsonProcessingException {
ConsoleLogger.printHeader("RELATIONSHIP SAMPLE");
String sampleBuildingModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.BUILDING_MODEL_ID, client, randomIntegerStringGenerator);
String sampleFloorModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.FLOOR_MODEL_ID, client, randomIntegerStringGenerator);
String buildingTwinId = UniqueIdHelper.getUniqueDigitalTwinId("buildingTwinId", client, randomIntegerStringGenerator);
String floorTwinId = UniqueIdHelper.getUniqueDigitalTwinId("floorTwinId", client, randomIntegerStringGenerator);
final String buildingFloorRelationshipId = "buildingFloorRelationshipId";
String buildingModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_RELATIONSHIP_PAYLOAD
.replace(SamplesConstants.MODEL_ID, sampleBuildingModelId)
.replace(SamplesConstants.MODEL_DISPLAY_NAME, "Building")
.replace(SamplesConstants.RELATIONSHIP_NAME, "contains")
.replace(SamplesConstants.RELATIONSHIP_TARGET_MODEL_ID, sampleFloorModelId);
String floorModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_RELATIONSHIP_PAYLOAD
.replace(SamplesConstants.MODEL_ID, sampleFloorModelId)
.replace(SamplesConstants.MODEL_DISPLAY_NAME, "Floor")
.replace(SamplesConstants.RELATIONSHIP_NAME, "containedIn")
.replace(SamplesConstants.RELATIONSHIP_TARGET_MODEL_ID, sampleBuildingModelId);
List<ModelData> createdModels = client.createModels(new ArrayList<>(Arrays.asList(buildingModelPayload, floorModelPayload)));
for (ModelData model : createdModels) {
ConsoleLogger.print("Created model " + model.getId());
}
BasicDigitalTwin buildingDigitalTwin = new BasicDigitalTwin()
.setId(buildingTwinId)
.setMetadata(new DigitalTwinMetadata()
.setModelId(sampleBuildingModelId));
client.createDigitalTwin(buildingTwinId, mapper.writeValueAsString(buildingDigitalTwin));
ConsoleLogger.print("Created twin" + buildingDigitalTwin.getId());
BasicDigitalTwin floorDigitalTwin = new BasicDigitalTwin()
.setId(floorTwinId)
.setMetadata(new DigitalTwinMetadata()
.setModelId(sampleFloorModelId));
client.createDigitalTwin(floorTwinId, mapper.writeValueAsString(floorDigitalTwin));
ConsoleLogger.print("Created twin" + floorDigitalTwin.getId());
ConsoleLogger.printHeader("Create relationships");
BasicRelationship buildingFloorRelationshipPayload = new BasicRelationship()
.setId(buildingFloorRelationshipId)
.setSourceId(buildingTwinId)
.setTargetId(floorTwinId)
.setName("contains")
.setCustomProperties("Prop1", "Prop1 value")
.setCustomProperties("Prop2", 6);
client.createRelationship(buildingTwinId, buildingFloorRelationshipId, mapper.writeValueAsString(buildingFloorRelationshipPayload));
ConsoleLogger.printSuccess("Created a digital twin relationship "+ buildingFloorRelationshipId + " from twin: " + buildingTwinId + " to twin: " + floorTwinId);
ConsoleLogger.printHeader("Get Relationship");
Response<BasicRelationship> getRelationshipRepsonse = client.getRelationshipWithResponse(
buildingTwinId,
buildingFloorRelationshipId,
BasicRelationship.class,
Context.NONE);
if (getRelationshipRepsonse.getStatusCode() == HttpURLConnection.HTTP_OK) {
BasicRelationship retrievedRelationship = getRelationshipRepsonse.getValue();
ConsoleLogger.printSuccess("Retrieved relationship: " + retrievedRelationship.getId() + " from twin: " + retrievedRelationship.getSourceId() + "\n\t" +
"Prop1: " + retrievedRelationship.getCustomProperties().get("Prop1") + "\n\t" +
"Prop2: " + retrievedRelationship.getCustomProperties().get("Prop2"));
}
ConsoleLogger.printHeader("List relationships");
PagedIterable<BasicRelationship> relationshipPages = client.listRelationships(buildingTwinId, BasicRelationship.class);
for (BasicRelationship relationship : relationshipPages) {
ConsoleLogger.printSuccess("Retrieved relationship: " + relationship.getId() + " with source: " + relationship.getSourceId() + " and target: " + relationship.getTargetId());
}
ConsoleLogger.printHeader("List incoming relationships");
PagedIterable<IncomingRelationship> incomingRelationships = client.listIncomingRelationships(floorTwinId);
for (IncomingRelationship incomingRelationship : incomingRelationships) {
ConsoleLogger.printSuccess("Found an incoming relationship: " + incomingRelationship.getRelationshipId() + " from: " + incomingRelationship.getSourceId());
}
ConsoleLogger.printHeader("Delete relationship");
client.deleteRelationship(buildingTwinId, buildingFloorRelationshipId);
ConsoleLogger.printSuccess("Deleted relationship: " + buildingFloorRelationshipId);
try {
client.deleteDigitalTwin(buildingTwinId);
client.deleteDigitalTwin(floorTwinId);
}
catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to delete digital twin due to" + ex);
}
try {
client.deleteModel(sampleBuildingModelId);
client.deleteModel(sampleFloorModelId);
}
catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to delete models due to" + ex);
}
} | if (getRelationshipRepsonse.getStatusCode() == HttpURLConnection.HTTP_OK) { | public static void runRelationshipsSample() throws JsonProcessingException {
ConsoleLogger.printHeader("RELATIONSHIP SAMPLE");
String sampleBuildingModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.BUILDING_MODEL_ID, client, randomIntegerStringGenerator);
String sampleFloorModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.FLOOR_MODEL_ID, client, randomIntegerStringGenerator);
String buildingTwinId = UniqueIdHelper.getUniqueDigitalTwinId("buildingTwinId", client, randomIntegerStringGenerator);
String floorTwinId = UniqueIdHelper.getUniqueDigitalTwinId("floorTwinId", client, randomIntegerStringGenerator);
final String buildingFloorRelationshipId = "buildingFloorRelationshipId";
String buildingModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_RELATIONSHIP_PAYLOAD
.replace(SamplesConstants.MODEL_ID, sampleBuildingModelId)
.replace(SamplesConstants.MODEL_DISPLAY_NAME, "Building")
.replace(SamplesConstants.RELATIONSHIP_NAME, "contains")
.replace(SamplesConstants.RELATIONSHIP_TARGET_MODEL_ID, sampleFloorModelId);
String floorModelPayload = SamplesConstants.TEMPORARY_MODEL_WITH_RELATIONSHIP_PAYLOAD
.replace(SamplesConstants.MODEL_ID, sampleFloorModelId)
.replace(SamplesConstants.MODEL_DISPLAY_NAME, "Floor")
.replace(SamplesConstants.RELATIONSHIP_NAME, "containedIn")
.replace(SamplesConstants.RELATIONSHIP_TARGET_MODEL_ID, sampleBuildingModelId);
List<ModelData> createdModels = client.createModels(new ArrayList<>(Arrays.asList(buildingModelPayload, floorModelPayload)));
for (ModelData model : createdModels) {
ConsoleLogger.print("Created model " + model.getId());
}
BasicDigitalTwin buildingDigitalTwin = new BasicDigitalTwin()
.setId(buildingTwinId)
.setMetadata(new DigitalTwinMetadata()
.setModelId(sampleBuildingModelId));
client.createDigitalTwin(buildingTwinId, mapper.writeValueAsString(buildingDigitalTwin));
ConsoleLogger.print("Created twin" + buildingDigitalTwin.getId());
BasicDigitalTwin floorDigitalTwin = new BasicDigitalTwin()
.setId(floorTwinId)
.setMetadata(new DigitalTwinMetadata()
.setModelId(sampleFloorModelId));
client.createDigitalTwin(floorTwinId, mapper.writeValueAsString(floorDigitalTwin));
ConsoleLogger.print("Created twin" + floorDigitalTwin.getId());
ConsoleLogger.printHeader("Create relationships");
BasicRelationship buildingFloorRelationshipPayload = new BasicRelationship()
.setId(buildingFloorRelationshipId)
.setSourceId(buildingTwinId)
.setTargetId(floorTwinId)
.setName("contains")
.setCustomProperties("Prop1", "Prop1 value")
.setCustomProperties("Prop2", 6);
client.createRelationship(buildingTwinId, buildingFloorRelationshipId, mapper.writeValueAsString(buildingFloorRelationshipPayload));
ConsoleLogger.printSuccess("Created a digital twin relationship "+ buildingFloorRelationshipId + " from twin: " + buildingTwinId + " to twin: " + floorTwinId);
ConsoleLogger.printHeader("Get Relationship");
Response<BasicRelationship> getRelationshipResponse = client.getRelationshipWithResponse(
buildingTwinId,
buildingFloorRelationshipId,
BasicRelationship.class,
Context.NONE);
if (getRelationshipResponse.getStatusCode() == HttpURLConnection.HTTP_OK) {
BasicRelationship retrievedRelationship = getRelationshipResponse.getValue();
ConsoleLogger.printSuccess("Retrieved relationship: " + retrievedRelationship.getId() + " from twin: " + retrievedRelationship.getSourceId() + "\n\t" +
"Prop1: " + retrievedRelationship.getCustomProperties().get("Prop1") + "\n\t" +
"Prop2: " + retrievedRelationship.getCustomProperties().get("Prop2"));
}
ConsoleLogger.printHeader("List relationships");
PagedIterable<BasicRelationship> relationshipPages = client.listRelationships(buildingTwinId, BasicRelationship.class);
for (BasicRelationship relationship : relationshipPages) {
ConsoleLogger.printSuccess("Retrieved relationship: " + relationship.getId() + " with source: " + relationship.getSourceId() + " and target: " + relationship.getTargetId());
}
ConsoleLogger.printHeader("List incoming relationships");
PagedIterable<IncomingRelationship> incomingRelationships = client.listIncomingRelationships(floorTwinId);
for (IncomingRelationship incomingRelationship : incomingRelationships) {
ConsoleLogger.printSuccess("Found an incoming relationship: " + incomingRelationship.getRelationshipId() + " from: " + incomingRelationship.getSourceId());
}
ConsoleLogger.printHeader("Delete relationship");
client.deleteRelationship(buildingTwinId, buildingFloorRelationshipId);
ConsoleLogger.printSuccess("Deleted relationship: " + buildingFloorRelationshipId);
try {
client.deleteDigitalTwin(buildingTwinId);
client.deleteDigitalTwin(floorTwinId);
}
catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to delete digital twin due to" + ex);
}
try {
client.deleteModel(sampleBuildingModelId);
client.deleteModel(sampleFloorModelId);
}
catch (ErrorResponseException ex) {
ConsoleLogger.printFatal("Failed to delete models due to" + ex);
}
} | class RelationshipsSyncSamples {
private static DigitalTwinsClient client;
private static final ObjectMapper mapper = new ObjectMapper();
public static Function<Integer, String> randomIntegerStringGenerator = (maxLength) -> {
int randInt = new Random().nextInt((int)Math.pow(10, 8) - 1) + 1;
return String.valueOf(randInt);
};
public static void main(String[] args) throws IOException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runRelationshipsSample();
}
@SuppressWarnings("rawtypes")
} | class RelationshipsSyncSamples {
private static DigitalTwinsClient client;
private static final ObjectMapper mapper = new ObjectMapper();
public static Function<Integer, String> randomIntegerStringGenerator = (maxLength) -> {
int randInt = new Random().nextInt((int)Math.pow(10, 8) - 1) + 1;
return String.valueOf(randInt);
};
public static void main(String[] args) throws IOException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.credential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runRelationshipsSample();
}
} |
No retry - that is why we chose this exception vs. GoneException. We don't want retries in this scenario | public RntbdRequestRecord request(final RntbdRequestArgs args) {
this.throwIfClosed();
int concurrentRequestSnapshot = this.concurrentRequests.incrementAndGet();
if (concurrentRequestSnapshot > this.maxConcurrentRequests) {
return FailFastRntbdRequestRecord.createAndFailFast(
args,
concurrentRequestSnapshot,
concurrentRequests,
metrics,
remoteAddress);
}
this.lastRequestNanoTime.set(args.nanoTimeCreated());
final RntbdRequestRecord record = this.write(args);
record.whenComplete((response, error) -> {
this.concurrentRequests.decrementAndGet();
this.metrics.markComplete(record);
});
return record;
} | return FailFastRntbdRequestRecord.createAndFailFast( | public RntbdRequestRecord request(final RntbdRequestArgs args) {
this.throwIfClosed();
int concurrentRequestSnapshot = this.concurrentRequests.incrementAndGet();
if (concurrentRequestSnapshot > this.maxConcurrentRequests) {
try {
return FailFastRntbdRequestRecord.createAndFailFast(
args,
concurrentRequestSnapshot,
metrics,
remoteAddress);
}
finally {
concurrentRequests.decrementAndGet();
}
}
this.lastRequestNanoTime.set(args.nanoTimeCreated());
final RntbdRequestRecord record = this.write(args);
record.whenComplete((response, error) -> {
this.concurrentRequests.decrementAndGet();
this.metrics.markComplete(record);
});
return record;
} | class RntbdServiceEndpoint implements RntbdEndpoint {
private static final String TAG_NAME = RntbdServiceEndpoint.class.getSimpleName();
private static final long QUIET_PERIOD = 2_000_000_000L;
private static final AtomicLong instanceCount = new AtomicLong();
private static final Logger logger = LoggerFactory.getLogger(RntbdServiceEndpoint.class);
private static final AdaptiveRecvByteBufAllocator receiveBufferAllocator = new AdaptiveRecvByteBufAllocator();
private final RntbdClientChannelPool channelPool;
private final AtomicBoolean closed;
private final AtomicInteger concurrentRequests;
private final long id;
private final AtomicLong lastRequestNanoTime;
private final RntbdMetrics metrics;
private final Provider provider;
private final SocketAddress remoteAddress;
private final RntbdRequestTimer requestTimer;
private final Tag tag;
private final int maxConcurrentRequests;
private RntbdServiceEndpoint(
final Provider provider,
final Config config,
final NioEventLoopGroup group,
final RntbdRequestTimer timer,
final URI physicalAddress) {
final Bootstrap bootstrap = new Bootstrap()
.channel(NioSocketChannel.class)
.group(group)
.option(ChannelOption.ALLOCATOR, config.allocator())
.option(ChannelOption.AUTO_READ, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutInMillis())
.option(ChannelOption.RCVBUF_ALLOCATOR, receiveBufferAllocator)
.option(ChannelOption.SO_KEEPALIVE, true)
.remoteAddress(physicalAddress.getHost(), physicalAddress.getPort());
this.channelPool = new RntbdClientChannelPool(this, bootstrap, config);
this.remoteAddress = bootstrap.config().remoteAddress();
this.concurrentRequests = new AtomicInteger();
this.lastRequestNanoTime = new AtomicLong(System.nanoTime());
this.closed = new AtomicBoolean();
this.requestTimer = timer;
this.tag = Tag.of(TAG_NAME, RntbdMetrics.escape(this.remoteAddress.toString()));
this.id = instanceCount.incrementAndGet();
this.provider = provider;
this.metrics = new RntbdMetrics(provider.transportClient, this);
this.maxConcurrentRequests = config.maxConcurrentRequestsPerEndpoint();
}
/**
* @return approximate number of acquired channels.
*/
@Override
public int channelsAcquiredMetric() {
return this.channelPool.channelsAcquiredMetrics();
}
/**
* @return approximate number of available channels.
*/
@Override
public int channelsAvailableMetric() {
return this.channelPool.channelsAvailableMetrics();
}
@Override
public int concurrentRequests() {
return this.concurrentRequests.get();
}
@Override
public long id() {
return this.id;
}
@Override
public boolean isClosed() {
return this.closed.get();
}
public long lastRequestNanoTime() {
return this.lastRequestNanoTime.get();
}
@Override
public SocketAddress remoteAddress() {
return this.remoteAddress;
}
@Override
public int requestQueueLength() {
return this.channelPool.requestQueueLength();
}
@Override
public Tag tag() {
return this.tag;
}
@Override
public long usedDirectMemory() {
return this.channelPool.usedDirectMemory();
}
@Override
public long usedHeapMemory() {
return this.channelPool.usedHeapMemory();
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
this.provider.evict(this);
this.channelPool.close();
}
}
@Override
public String toString() {
return RntbdObjectMapper.toString(this);
}
private void ensureSuccessWhenReleasedToPool(Channel channel, Future<Void> released) {
if (released.isSuccess()) {
logger.debug("\n [{}]\n {}\n release succeeded", this, channel);
} else {
logger.debug("\n [{}]\n {}\n release failed due to {}", this, channel, released.cause());
}
}
private void releaseToPool(final Channel channel) {
logger.debug("\n [{}]\n {}\n RELEASE", this, channel);
final Future<Void> released = this.channelPool.release(channel);
if (logger.isDebugEnabled()) {
if (released.isDone()) {
ensureSuccessWhenReleasedToPool(channel, released);
} else {
released.addListener(ignored -> ensureSuccessWhenReleasedToPool(channel, released));
}
}
}
private void throwIfClosed() {
checkState(!this.closed.get(), "%s is closed", this);
}
private RntbdRequestRecord write(final RntbdRequestArgs requestArgs) {
final RntbdRequestRecord requestRecord = new AsyncRntbdRequestRecord(requestArgs, this.requestTimer);
final Future<Channel> connectedChannel = this.channelPool.acquire();
logger.debug("\n [{}]\n {}\n WRITE WHEN CONNECTED {}", this, requestArgs, connectedChannel);
if (connectedChannel.isDone()) {
return writeWhenConnected(requestRecord, connectedChannel);
} else {
connectedChannel.addListener(ignored -> writeWhenConnected(requestRecord, connectedChannel));
}
return requestRecord;
}
private RntbdRequestRecord writeWhenConnected(
final RntbdRequestRecord requestRecord, final Future<? super Channel> connected) {
if (connected.isSuccess()) {
final Channel channel = (Channel) connected.getNow();
assert channel != null : "impossible";
this.releaseToPool(channel);
channel.write(requestRecord.stage(RntbdRequestRecord.Stage.PIPELINED));
return requestRecord;
}
final RntbdRequestArgs requestArgs = requestRecord.args();
final UUID activityId = requestArgs.activityId();
final Throwable cause = connected.cause();
if (connected.isCancelled()) {
logger.debug("\n [{}]\n {}\n write cancelled: {}", this, requestArgs, cause);
requestRecord.cancel(true);
} else {
logger.debug("\n [{}]\n {}\n write failed due to {} ", this, requestArgs, cause);
final String reason = cause.toString();
final GoneException goneException = new GoneException(
lenientFormat("failed to establish connection to %s due to %s", this.remoteAddress, reason),
cause instanceof Exception ? (Exception) cause : new IOException(reason, cause),
ImmutableMap.of(HttpHeaders.ACTIVITY_ID, activityId.toString()),
requestArgs.replicaPath()
);
BridgeInternal.setRequestHeaders(goneException, requestArgs.serviceRequest().getHeaders());
requestRecord.completeExceptionally(goneException);
}
return requestRecord;
}
static final class JsonSerializer extends StdSerializer<RntbdServiceEndpoint> {
private static final long serialVersionUID = -5764954918168771152L;
public JsonSerializer() {
super(RntbdServiceEndpoint.class);
}
@Override
public void serialize(RntbdServiceEndpoint value, JsonGenerator generator, SerializerProvider provider)
throws IOException {
generator.writeStartObject();
generator.writeNumberField("id", value.id);
generator.writeBooleanField("isClosed", value.isClosed());
generator.writeNumberField("concurrentRequests", value.concurrentRequests());
generator.writeStringField("remoteAddress", value.remoteAddress.toString());
generator.writeObjectField("channelPool", value.channelPool);
generator.writeEndObject();
}
}
public static final class Provider implements RntbdEndpoint.Provider {
private static final Logger logger = LoggerFactory.getLogger(Provider.class);
private final AtomicBoolean closed;
private final Config config;
private final ConcurrentHashMap<String, RntbdEndpoint> endpoints;
private final NioEventLoopGroup eventLoopGroup;
private final AtomicInteger evictions;
private final RntbdRequestTimer requestTimer;
private final RntbdTransportClient transportClient;
public Provider(
final RntbdTransportClient transportClient,
final Options options,
final SslContext sslContext) {
checkNotNull(transportClient, "expected non-null provider");
checkNotNull(options, "expected non-null options");
checkNotNull(sslContext, "expected non-null sslContext");
final DefaultThreadFactory threadFactory = new DefaultThreadFactory("cosmos-rntbd-nio", true);
final LogLevel wireLogLevel;
if (logger.isDebugEnabled()) {
wireLogLevel = LogLevel.TRACE;
} else {
wireLogLevel = null;
}
this.transportClient = transportClient;
this.config = new Config(options, sslContext, wireLogLevel);
this.requestTimer = new RntbdRequestTimer(
config.requestTimeoutInNanos(),
config.requestTimerResolutionInNanos());
this.eventLoopGroup = new NioEventLoopGroup(options.threadCount(), threadFactory);
this.endpoints = new ConcurrentHashMap<>();
this.evictions = new AtomicInteger();
this.closed = new AtomicBoolean();
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
for (final RntbdEndpoint endpoint : this.endpoints.values()) {
endpoint.close();
}
this.eventLoopGroup.shutdownGracefully(QUIET_PERIOD, this.config.shutdownTimeoutInNanos(), NANOSECONDS)
.addListener(future -> {
this.requestTimer.close();
if (future.isSuccess()) {
logger.debug("\n [{}]\n closed endpoints", this);
return;
}
logger.error("\n [{}]\n failed to close endpoints due to ", this, future.cause());
});
return;
}
logger.debug("\n [{}]\n already closed", this);
}
@Override
public Config config() {
return this.config;
}
@Override
public int count() {
return this.endpoints.size();
}
@Override
public int evictions() {
return this.evictions.get();
}
@Override
public RntbdEndpoint get(final URI physicalAddress) {
return endpoints.computeIfAbsent(physicalAddress.getAuthority(), authority -> new RntbdServiceEndpoint(
this,
this.config,
this.eventLoopGroup,
this.requestTimer,
physicalAddress));
}
@Override
public Stream<RntbdEndpoint> list() {
return this.endpoints.values().stream();
}
private void evict(final RntbdEndpoint endpoint) {
if (this.endpoints.remove(endpoint.remoteAddress().toString()) != null) {
this.evictions.incrementAndGet();
}
}
}
} | class RntbdServiceEndpoint implements RntbdEndpoint {
private static final String TAG_NAME = RntbdServiceEndpoint.class.getSimpleName();
private static final long QUIET_PERIOD = 2_000_000_000L;
private static final AtomicLong instanceCount = new AtomicLong();
private static final Logger logger = LoggerFactory.getLogger(RntbdServiceEndpoint.class);
private static final AdaptiveRecvByteBufAllocator receiveBufferAllocator = new AdaptiveRecvByteBufAllocator();
private final RntbdClientChannelPool channelPool;
private final AtomicBoolean closed;
private final AtomicInteger concurrentRequests;
private final long id;
private final AtomicLong lastRequestNanoTime;
private final RntbdMetrics metrics;
private final Provider provider;
private final SocketAddress remoteAddress;
private final RntbdRequestTimer requestTimer;
private final Tag tag;
private final int maxConcurrentRequests;
private RntbdServiceEndpoint(
final Provider provider,
final Config config,
final NioEventLoopGroup group,
final RntbdRequestTimer timer,
final URI physicalAddress) {
final Bootstrap bootstrap = new Bootstrap()
.channel(NioSocketChannel.class)
.group(group)
.option(ChannelOption.ALLOCATOR, config.allocator())
.option(ChannelOption.AUTO_READ, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutInMillis())
.option(ChannelOption.RCVBUF_ALLOCATOR, receiveBufferAllocator)
.option(ChannelOption.SO_KEEPALIVE, true)
.remoteAddress(physicalAddress.getHost(), physicalAddress.getPort());
this.channelPool = new RntbdClientChannelPool(this, bootstrap, config);
this.remoteAddress = bootstrap.config().remoteAddress();
this.concurrentRequests = new AtomicInteger();
this.lastRequestNanoTime = new AtomicLong(System.nanoTime());
this.closed = new AtomicBoolean();
this.requestTimer = timer;
this.tag = Tag.of(TAG_NAME, RntbdMetrics.escape(this.remoteAddress.toString()));
this.id = instanceCount.incrementAndGet();
this.provider = provider;
this.metrics = new RntbdMetrics(provider.transportClient, this);
this.maxConcurrentRequests = config.maxConcurrentRequestsPerEndpoint();
}
/**
* @return approximate number of acquired channels.
*/
@Override
public int channelsAcquiredMetric() {
return this.channelPool.channelsAcquiredMetrics();
}
/**
* @return approximate number of available channels.
*/
@Override
public int channelsAvailableMetric() {
return this.channelPool.channelsAvailableMetrics();
}
@Override
public int concurrentRequests() {
return this.concurrentRequests.get();
}
@Override
public long id() {
return this.id;
}
@Override
public boolean isClosed() {
return this.closed.get();
}
public long lastRequestNanoTime() {
return this.lastRequestNanoTime.get();
}
@Override
public SocketAddress remoteAddress() {
return this.remoteAddress;
}
@Override
public int requestQueueLength() {
return this.channelPool.requestQueueLength();
}
@Override
public Tag tag() {
return this.tag;
}
@Override
public long usedDirectMemory() {
return this.channelPool.usedDirectMemory();
}
@Override
public long usedHeapMemory() {
return this.channelPool.usedHeapMemory();
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
this.provider.evict(this);
this.channelPool.close();
}
}
@Override
public String toString() {
return RntbdObjectMapper.toString(this);
}
private void ensureSuccessWhenReleasedToPool(Channel channel, Future<Void> released) {
if (released.isSuccess()) {
logger.debug("\n [{}]\n {}\n release succeeded", this, channel);
} else {
logger.debug("\n [{}]\n {}\n release failed due to {}", this, channel, released.cause());
}
}
private void releaseToPool(final Channel channel) {
logger.debug("\n [{}]\n {}\n RELEASE", this, channel);
final Future<Void> released = this.channelPool.release(channel);
if (logger.isDebugEnabled()) {
if (released.isDone()) {
ensureSuccessWhenReleasedToPool(channel, released);
} else {
released.addListener(ignored -> ensureSuccessWhenReleasedToPool(channel, released));
}
}
}
private void throwIfClosed() {
checkState(!this.closed.get(), "%s is closed", this);
}
private RntbdRequestRecord write(final RntbdRequestArgs requestArgs) {
final RntbdRequestRecord requestRecord = new AsyncRntbdRequestRecord(requestArgs, this.requestTimer);
final Future<Channel> connectedChannel = this.channelPool.acquire();
logger.debug("\n [{}]\n {}\n WRITE WHEN CONNECTED {}", this, requestArgs, connectedChannel);
if (connectedChannel.isDone()) {
return writeWhenConnected(requestRecord, connectedChannel);
} else {
connectedChannel.addListener(ignored -> writeWhenConnected(requestRecord, connectedChannel));
}
return requestRecord;
}
private RntbdRequestRecord writeWhenConnected(
final RntbdRequestRecord requestRecord, final Future<? super Channel> connected) {
if (connected.isSuccess()) {
final Channel channel = (Channel) connected.getNow();
assert channel != null : "impossible";
this.releaseToPool(channel);
channel.write(requestRecord.stage(RntbdRequestRecord.Stage.PIPELINED));
return requestRecord;
}
final RntbdRequestArgs requestArgs = requestRecord.args();
final UUID activityId = requestArgs.activityId();
final Throwable cause = connected.cause();
if (connected.isCancelled()) {
logger.debug("\n [{}]\n {}\n write cancelled: {}", this, requestArgs, cause);
requestRecord.cancel(true);
} else {
logger.debug("\n [{}]\n {}\n write failed due to {} ", this, requestArgs, cause);
final String reason = cause.toString();
final GoneException goneException = new GoneException(
lenientFormat("failed to establish connection to %s due to %s", this.remoteAddress, reason),
cause instanceof Exception ? (Exception) cause : new IOException(reason, cause),
ImmutableMap.of(HttpHeaders.ACTIVITY_ID, activityId.toString()),
requestArgs.replicaPath()
);
BridgeInternal.setRequestHeaders(goneException, requestArgs.serviceRequest().getHeaders());
requestRecord.completeExceptionally(goneException);
}
return requestRecord;
}
static final class JsonSerializer extends StdSerializer<RntbdServiceEndpoint> {
private static final long serialVersionUID = -5764954918168771152L;
public JsonSerializer() {
super(RntbdServiceEndpoint.class);
}
@Override
public void serialize(RntbdServiceEndpoint value, JsonGenerator generator, SerializerProvider provider)
throws IOException {
generator.writeStartObject();
generator.writeNumberField("id", value.id);
generator.writeBooleanField("isClosed", value.isClosed());
generator.writeNumberField("concurrentRequests", value.concurrentRequests());
generator.writeStringField("remoteAddress", value.remoteAddress.toString());
generator.writeObjectField("channelPool", value.channelPool);
generator.writeEndObject();
}
}
public static final class Provider implements RntbdEndpoint.Provider {
private static final Logger logger = LoggerFactory.getLogger(Provider.class);
private final AtomicBoolean closed;
private final Config config;
private final ConcurrentHashMap<String, RntbdEndpoint> endpoints;
private final NioEventLoopGroup eventLoopGroup;
private final AtomicInteger evictions;
private final RntbdRequestTimer requestTimer;
private final RntbdTransportClient transportClient;
public Provider(
final RntbdTransportClient transportClient,
final Options options,
final SslContext sslContext) {
checkNotNull(transportClient, "expected non-null provider");
checkNotNull(options, "expected non-null options");
checkNotNull(sslContext, "expected non-null sslContext");
final DefaultThreadFactory threadFactory = new DefaultThreadFactory("cosmos-rntbd-nio", true);
final LogLevel wireLogLevel;
if (logger.isDebugEnabled()) {
wireLogLevel = LogLevel.TRACE;
} else {
wireLogLevel = null;
}
this.transportClient = transportClient;
this.config = new Config(options, sslContext, wireLogLevel);
this.requestTimer = new RntbdRequestTimer(
config.requestTimeoutInNanos(),
config.requestTimerResolutionInNanos());
this.eventLoopGroup = new NioEventLoopGroup(options.threadCount(), threadFactory);
this.endpoints = new ConcurrentHashMap<>();
this.evictions = new AtomicInteger();
this.closed = new AtomicBoolean();
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
for (final RntbdEndpoint endpoint : this.endpoints.values()) {
endpoint.close();
}
this.eventLoopGroup.shutdownGracefully(QUIET_PERIOD, this.config.shutdownTimeoutInNanos(), NANOSECONDS)
.addListener(future -> {
this.requestTimer.close();
if (future.isSuccess()) {
logger.debug("\n [{}]\n closed endpoints", this);
return;
}
logger.error("\n [{}]\n failed to close endpoints due to ", this, future.cause());
});
return;
}
logger.debug("\n [{}]\n already closed", this);
}
@Override
public Config config() {
return this.config;
}
@Override
public int count() {
return this.endpoints.size();
}
@Override
public int evictions() {
return this.evictions.get();
}
@Override
public RntbdEndpoint get(final URI physicalAddress) {
return endpoints.computeIfAbsent(physicalAddress.getAuthority(), authority -> new RntbdServiceEndpoint(
this,
this.config,
this.eventLoopGroup,
this.requestTimer,
physicalAddress));
}
@Override
public Stream<RntbdEndpoint> list() {
return this.endpoints.values().stream();
}
private void evict(final RntbdEndpoint endpoint) {
if (this.endpoints.remove(endpoint.remoteAddress().toString()) != null) {
this.evictions.incrementAndGet();
}
}
}
} |
IoT Hub query tests add a buffer or retry to account for any sort of propagation delay between when a twin is created and when query can find it. Does this test pass reliably? | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
try {
String roomModelPayload = TestAssetsHelper.getRoomModelPayload(roomModelId, floorModelId);
StepVerifier.create(asyncClient.createModels(new ArrayList<>(Arrays.asList(roomModelPayload))))
.assertNext(response ->
assertThat(response.size())
.as("Created models successfully")
.isEqualTo(1))
.verifyComplete();
String roomTwin = TestAssetsHelper.getRoomTwinPayload(roomModelId);
StepVerifier.create(asyncClient.createDigitalTwinWithResponse(roomTwinId, roomTwin))
.assertNext(response ->
assertThat(response.getStatusCode())
.as("Created digitaltwin successfully")
.isEqualTo(HttpURLConnection.HTTP_OK))
.verifyComplete();
String queryString = "SELECT * FROM digitaltwins where IsOccupied = true";
StepVerifier.create(asyncClient.query(queryString, BasicDigitalTwin.class))
.thenConsumeWhile(dt -> {
assertThat(dt.getCustomProperties().get("IsOccupied"))
.as("IsOccupied should be true")
.isEqualTo(true);
return true;
})
.verifyComplete();
}
finally {
try {
if (roomTwinId != null) {
asyncClient.deleteDigitalTwin(roomTwinId).block();
}
if (roomModelId != null){
asyncClient.deleteModel(roomModelId).block();
}
}
catch (Exception ex)
{
fail("Failed to cleanup due to: ", ex);
}
}
} | StepVerifier.create(asyncClient.query(queryString, BasicDigitalTwin.class)) | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
try {
String roomModelPayload = TestAssetsHelper.getRoomModelPayload(roomModelId, floorModelId);
StepVerifier.create(asyncClient.createModels(new ArrayList<>(Arrays.asList(roomModelPayload))))
.assertNext(response ->
assertThat(response.size())
.as("Created models successfully")
.isEqualTo(1))
.verifyComplete();
String roomTwin = TestAssetsHelper.getRoomTwinPayload(roomModelId);
StepVerifier.create(asyncClient.createDigitalTwinWithResponse(roomTwinId, roomTwin))
.assertNext(response ->
assertThat(response.getStatusCode())
.as("Created digitaltwin successfully")
.isEqualTo(HttpURLConnection.HTTP_OK))
.verifyComplete();
String queryString = "SELECT * FROM digitaltwins where IsOccupied = true";
StepVerifier.create(asyncClient.query(queryString, BasicDigitalTwin.class))
.thenConsumeWhile(dt -> {
assertThat(dt.getCustomProperties().get("IsOccupied"))
.as("IsOccupied should be true")
.isEqualTo(true);
return true;
})
.verifyComplete();
}
finally {
try {
if (roomTwinId != null) {
asyncClient.deleteDigitalTwin(roomTwinId).block();
}
if (roomModelId != null){
asyncClient.deleteModel(roomModelId).block();
}
}
catch (Exception ex)
{
fail("Failed to cleanup due to: ", ex);
}
}
} | class QueryAsyncTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class QueryAsyncTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
Yes it does. If we see flakiness later we can add some idle time. | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
try {
String roomModelPayload = TestAssetsHelper.getRoomModelPayload(roomModelId, floorModelId);
StepVerifier.create(asyncClient.createModels(new ArrayList<>(Arrays.asList(roomModelPayload))))
.assertNext(response ->
assertThat(response.size())
.as("Created models successfully")
.isEqualTo(1))
.verifyComplete();
String roomTwin = TestAssetsHelper.getRoomTwinPayload(roomModelId);
StepVerifier.create(asyncClient.createDigitalTwinWithResponse(roomTwinId, roomTwin))
.assertNext(response ->
assertThat(response.getStatusCode())
.as("Created digitaltwin successfully")
.isEqualTo(HttpURLConnection.HTTP_OK))
.verifyComplete();
String queryString = "SELECT * FROM digitaltwins where IsOccupied = true";
StepVerifier.create(asyncClient.query(queryString, BasicDigitalTwin.class))
.thenConsumeWhile(dt -> {
assertThat(dt.getCustomProperties().get("IsOccupied"))
.as("IsOccupied should be true")
.isEqualTo(true);
return true;
})
.verifyComplete();
}
finally {
try {
if (roomTwinId != null) {
asyncClient.deleteDigitalTwin(roomTwinId).block();
}
if (roomModelId != null){
asyncClient.deleteModel(roomModelId).block();
}
}
catch (Exception ex)
{
fail("Failed to cleanup due to: ", ex);
}
}
} | StepVerifier.create(asyncClient.query(queryString, BasicDigitalTwin.class)) | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_MODEL_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
String roomTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_TWIN_ID_PREFIX, asyncClient, randomIntegerStringGenerator);
try {
String roomModelPayload = TestAssetsHelper.getRoomModelPayload(roomModelId, floorModelId);
StepVerifier.create(asyncClient.createModels(new ArrayList<>(Arrays.asList(roomModelPayload))))
.assertNext(response ->
assertThat(response.size())
.as("Created models successfully")
.isEqualTo(1))
.verifyComplete();
String roomTwin = TestAssetsHelper.getRoomTwinPayload(roomModelId);
StepVerifier.create(asyncClient.createDigitalTwinWithResponse(roomTwinId, roomTwin))
.assertNext(response ->
assertThat(response.getStatusCode())
.as("Created digitaltwin successfully")
.isEqualTo(HttpURLConnection.HTTP_OK))
.verifyComplete();
String queryString = "SELECT * FROM digitaltwins where IsOccupied = true";
StepVerifier.create(asyncClient.query(queryString, BasicDigitalTwin.class))
.thenConsumeWhile(dt -> {
assertThat(dt.getCustomProperties().get("IsOccupied"))
.as("IsOccupied should be true")
.isEqualTo(true);
return true;
})
.verifyComplete();
}
finally {
try {
if (roomTwinId != null) {
asyncClient.deleteDigitalTwin(roomTwinId).block();
}
if (roomModelId != null){
asyncClient.deleteModel(roomModelId).block();
}
}
catch (Exception ex)
{
fail("Failed to cleanup due to: ", ex);
}
}
} | class QueryAsyncTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class QueryAsyncTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
You can move the try down until the digital twin is created successfully. If the finally block executes before the digital twin is created, the thrown exception will just be "Failed to delete digital twin" rather than the exception that caused the pre-mature finally block | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
String roomModelPayload = TestAssetsHelper.getRoomModelPayload(roomModelId, floorModelId);
client.createModelsWithResponse(new ArrayList<>(Arrays.asList(roomModelPayload)), Context.NONE);
String roomTwin = TestAssetsHelper.getRoomTwinPayload(roomModelId);
client.createDigitalTwinWithResponse(roomTwinId, roomTwin, Context.NONE);
String queryString = "SELECT * FROM digitaltwins where IsOccupied = true";
PagedIterable<BasicDigitalTwin> pagedQueryResponse = client.query(queryString, BasicDigitalTwin.class);
for(BasicDigitalTwin digitalTwin : pagedQueryResponse){
assertThat(digitalTwin.getCustomProperties().get("IsOccupied"))
.as("IsOccupied should be true")
.isEqualTo(true);
}
}
finally {
try {
if (roomTwinId != null) {
client.deleteDigitalTwin(roomTwinId);
}
if (roomModelId != null){
client.deleteModel(roomModelId);
}
}
catch (Exception ex)
{
fail("Failed to cleanup due to: ", ex);
}
}
} | try { | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
String roomModelPayload = TestAssetsHelper.getRoomModelPayload(roomModelId, floorModelId);
client.createModelsWithResponse(new ArrayList<>(Arrays.asList(roomModelPayload)), Context.NONE);
String roomTwin = TestAssetsHelper.getRoomTwinPayload(roomModelId);
client.createDigitalTwinWithResponse(roomTwinId, roomTwin, Context.NONE);
String queryString = "SELECT * FROM digitaltwins where IsOccupied = true";
PagedIterable<BasicDigitalTwin> pagedQueryResponse = client.query(queryString, BasicDigitalTwin.class);
for(BasicDigitalTwin digitalTwin : pagedQueryResponse){
assertThat(digitalTwin.getCustomProperties().get("IsOccupied"))
.as("IsOccupied should be true")
.isEqualTo(true);
}
}
finally {
try {
if (roomTwinId != null) {
client.deleteDigitalTwin(roomTwinId);
}
if (roomModelId != null){
client.deleteModel(roomModelId);
}
}
catch (Exception ex)
{
fail("Failed to cleanup due to: ", ex);
}
}
} | class QueryTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class QueryTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
yes, but then if the digitaltwin fails to create it will not get to the finally block that will delete the model ... | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
String roomModelPayload = TestAssetsHelper.getRoomModelPayload(roomModelId, floorModelId);
client.createModelsWithResponse(new ArrayList<>(Arrays.asList(roomModelPayload)), Context.NONE);
String roomTwin = TestAssetsHelper.getRoomTwinPayload(roomModelId);
client.createDigitalTwinWithResponse(roomTwinId, roomTwin, Context.NONE);
String queryString = "SELECT * FROM digitaltwins where IsOccupied = true";
PagedIterable<BasicDigitalTwin> pagedQueryResponse = client.query(queryString, BasicDigitalTwin.class);
for(BasicDigitalTwin digitalTwin : pagedQueryResponse){
assertThat(digitalTwin.getCustomProperties().get("IsOccupied"))
.as("IsOccupied should be true")
.isEqualTo(true);
}
}
finally {
try {
if (roomTwinId != null) {
client.deleteDigitalTwin(roomTwinId);
}
if (roomModelId != null){
client.deleteModel(roomModelId);
}
}
catch (Exception ex)
{
fail("Failed to cleanup due to: ", ex);
}
}
} | try { | public void validQuerySucceeds(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.ROOM_MODEL_ID_PREFIX, client, randomIntegerStringGenerator);
String roomTwinId = UniqueIdHelper.getUniqueDigitalTwinId(TestAssetDefaults.ROOM_TWIN_ID_PREFIX, client, randomIntegerStringGenerator);
try {
String roomModelPayload = TestAssetsHelper.getRoomModelPayload(roomModelId, floorModelId);
client.createModelsWithResponse(new ArrayList<>(Arrays.asList(roomModelPayload)), Context.NONE);
String roomTwin = TestAssetsHelper.getRoomTwinPayload(roomModelId);
client.createDigitalTwinWithResponse(roomTwinId, roomTwin, Context.NONE);
String queryString = "SELECT * FROM digitaltwins where IsOccupied = true";
PagedIterable<BasicDigitalTwin> pagedQueryResponse = client.query(queryString, BasicDigitalTwin.class);
for(BasicDigitalTwin digitalTwin : pagedQueryResponse){
assertThat(digitalTwin.getCustomProperties().get("IsOccupied"))
.as("IsOccupied should be true")
.isEqualTo(true);
}
}
finally {
try {
if (roomTwinId != null) {
client.deleteDigitalTwin(roomTwinId);
}
if (roomModelId != null){
client.deleteModel(roomModelId);
}
}
catch (Exception ex)
{
fail("Failed to cleanup due to: ", ex);
}
}
} | class QueryTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} | class QueryTests extends QueryTestBase{
private final ClientLogger logger = new ClientLogger(ComponentsTests.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
} |
Seems just `indexable.id()`? | private Mono<ServicePrincipal> submitRolesAsync(final ServicePrincipal servicePrincipal) {
Mono<ServicePrincipal> create;
if (rolesToCreate.isEmpty()) {
create = Mono.just(servicePrincipal);
} else {
create =
Flux
.fromIterable(rolesToCreate.entrySet())
.flatMap(
roleEntry ->
manager()
.roleAssignments()
.define(this.manager().sdkContext().randomUuid())
.forServicePrincipal(servicePrincipal)
.withBuiltInRole(roleEntry.getValue())
.withScope(roleEntry.getKey())
.createAsync())
.doOnNext(
indexable ->
cachedRoleAssignments.put((indexable).id(), indexable))
.last()
.map(
indexable -> {
rolesToCreate.clear();
return servicePrincipal;
});
}
Mono<ServicePrincipal> delete;
if (rolesToDelete.isEmpty()) {
delete = Mono.just(servicePrincipal);
} else {
delete =
Flux
.fromIterable(rolesToDelete)
.flatMap(
role ->
manager()
.roleAssignments()
.deleteByIdAsync(cachedRoleAssignments.get(role).id())
.thenReturn(role))
.doOnNext(s -> cachedRoleAssignments.remove(s))
.last()
.map(
s -> {
rolesToDelete.clear();
return servicePrincipal;
});
}
return create.mergeWith(delete).last();
} | cachedRoleAssignments.put((indexable).id(), indexable)) | private Mono<ServicePrincipal> submitRolesAsync(final ServicePrincipal servicePrincipal) {
Mono<ServicePrincipal> create;
if (rolesToCreate.isEmpty()) {
create = Mono.just(servicePrincipal);
} else {
create =
Flux
.fromIterable(rolesToCreate.entrySet())
.flatMap(
roleEntry ->
manager()
.roleAssignments()
.define(this.manager().sdkContext().randomUuid())
.forServicePrincipal(servicePrincipal)
.withBuiltInRole(roleEntry.getValue())
.withScope(roleEntry.getKey())
.createAsync())
.doOnNext(
indexable ->
cachedRoleAssignments.put(indexable.id(), indexable))
.last()
.map(
indexable -> {
rolesToCreate.clear();
return servicePrincipal;
});
}
Mono<ServicePrincipal> delete;
if (rolesToDelete.isEmpty()) {
delete = Mono.just(servicePrincipal);
} else {
delete =
Flux
.fromIterable(rolesToDelete)
.flatMap(
role ->
manager()
.roleAssignments()
.deleteByIdAsync(cachedRoleAssignments.get(role).id())
.thenReturn(role))
.doOnNext(s -> cachedRoleAssignments.remove(s))
.last()
.map(
s -> {
rolesToDelete.clear();
return servicePrincipal;
});
}
return create.mergeWith(delete).last();
} | class ServicePrincipalImpl extends CreatableUpdatableImpl<ServicePrincipal, ServicePrincipalInner, ServicePrincipalImpl>
implements ServicePrincipal,
ServicePrincipal.Definition,
ServicePrincipal.Update,
HasCredential<ServicePrincipalImpl> {
private AuthorizationManager manager;
private Map<String, PasswordCredential> cachedPasswordCredentials;
private Map<String, CertificateCredential> cachedCertificateCredentials;
private Map<String, RoleAssignment> cachedRoleAssignments;
private ServicePrincipalCreateParameters createParameters;
private Creatable<ActiveDirectoryApplication> applicationCreatable;
private Map<String, BuiltInRole> rolesToCreate;
private Set<String> rolesToDelete;
String assignedSubscription;
private List<CertificateCredentialImpl<?>> certificateCredentialsToCreate;
private List<PasswordCredentialImpl<?>> passwordCredentialsToCreate;
private Set<String> certificateCredentialsToDelete;
private Set<String> passwordCredentialsToDelete;
ServicePrincipalImpl(ServicePrincipalInner innerObject, AuthorizationManager manager) {
super(innerObject.displayName(), innerObject);
this.manager = manager;
this.createParameters = new ServicePrincipalCreateParameters();
this.createParameters.withAccountEnabled(true);
this.cachedRoleAssignments = new HashMap<>();
this.rolesToCreate = new HashMap<>();
this.rolesToDelete = new HashSet<>();
this.cachedCertificateCredentials = new HashMap<>();
this.certificateCredentialsToCreate = new ArrayList<>();
this.certificateCredentialsToDelete = new HashSet<>();
this.cachedPasswordCredentials = new HashMap<>();
this.passwordCredentialsToCreate = new ArrayList<>();
this.passwordCredentialsToDelete = new HashSet<>();
}
@Override
public String applicationId() {
return inner().appId();
}
@Override
public List<String> servicePrincipalNames() {
return inner().servicePrincipalNames();
}
@Override
public Map<String, PasswordCredential> passwordCredentials() {
return Collections.unmodifiableMap(cachedPasswordCredentials);
}
@Override
public Map<String, CertificateCredential> certificateCredentials() {
return Collections.unmodifiableMap(cachedCertificateCredentials);
}
@Override
public Set<RoleAssignment> roleAssignments() {
return Collections.unmodifiableSet(new HashSet<>(cachedRoleAssignments.values()));
}
@Override
protected Mono<ServicePrincipalInner> getInnerAsync() {
return manager.inner().getServicePrincipals().getAsync(id());
}
@Override
public Mono<ServicePrincipal> createResourceAsync() {
Mono<ServicePrincipal> sp = Mono.just(this);
if (isInCreateMode()) {
if (applicationCreatable != null) {
ActiveDirectoryApplication application = this.taskResult(applicationCreatable.key());
createParameters.withAppId(application.applicationId());
}
sp = manager.inner().getServicePrincipals().createAsync(createParameters).map(innerToFluentMap(this));
}
return sp
.flatMap(
servicePrincipal ->
submitCredentialsAsync(servicePrincipal).mergeWith(submitRolesAsync(servicePrincipal)).last())
.map(
servicePrincipal -> {
for (PasswordCredentialImpl<?> passwordCredential : passwordCredentialsToCreate) {
passwordCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
}
for (CertificateCredentialImpl<?> certificateCredential : certificateCredentialsToCreate) {
certificateCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
}
passwordCredentialsToCreate.clear();
certificateCredentialsToCreate.clear();
return servicePrincipal;
});
}
private Mono<ServicePrincipal> submitCredentialsAsync(final ServicePrincipal sp) {
Mono<ServicePrincipal> mono = Mono.empty();
if (!certificateCredentialsToCreate.isEmpty() || !certificateCredentialsToDelete.isEmpty()) {
Map<String, CertificateCredential> newCerts = new HashMap<>(cachedCertificateCredentials);
for (String delete : certificateCredentialsToDelete) {
newCerts.remove(delete);
}
for (CertificateCredential create : certificateCredentialsToCreate) {
newCerts.put(create.name(), create);
}
List<KeyCredentialInner> updateKeyCredentials = new ArrayList<>();
for (CertificateCredential certificateCredential : newCerts.values()) {
updateKeyCredentials.add(certificateCredential.inner());
}
mono =
mono
.concatWith(
manager()
.inner()
.getServicePrincipals()
.updateKeyCredentialsAsync(sp.id(), updateKeyCredentials)
.then(Mono.just(ServicePrincipalImpl.this)))
.last();
}
if (!passwordCredentialsToCreate.isEmpty() || !passwordCredentialsToDelete.isEmpty()) {
Map<String, PasswordCredential> newPasses = new HashMap<>(cachedPasswordCredentials);
for (String delete : passwordCredentialsToDelete) {
newPasses.remove(delete);
}
for (PasswordCredential create : passwordCredentialsToCreate) {
newPasses.put(create.name(), create);
}
List<PasswordCredentialInner> updatePasswordCredentials = new ArrayList<>();
for (PasswordCredential passwordCredential : newPasses.values()) {
updatePasswordCredentials.add(passwordCredential.inner());
}
mono =
mono
.concatWith(
manager()
.inner()
.getServicePrincipals()
.updatePasswordCredentialsAsync(sp.id(), updatePasswordCredentials)
.then(Mono.just(ServicePrincipalImpl.this)))
.last();
}
return mono
.flatMap(
servicePrincipal -> {
passwordCredentialsToDelete.clear();
certificateCredentialsToDelete.clear();
return refreshCredentialsAsync();
});
}
@Override
public boolean isInCreateMode() {
return id() == null;
}
Mono<ServicePrincipal> refreshCredentialsAsync() {
return Mono
.just(ServicePrincipalImpl.this)
.map(
(Function<ServicePrincipalImpl, ServicePrincipal>)
servicePrincipal -> {
servicePrincipal.cachedCertificateCredentials.clear();
servicePrincipal.cachedPasswordCredentials.clear();
return servicePrincipal;
})
.concatWith(
manager()
.inner()
.getServicePrincipals()
.listKeyCredentialsAsync(id())
.map(
keyCredentialInner -> {
CertificateCredential credential = new CertificateCredentialImpl<>(keyCredentialInner);
ServicePrincipalImpl.this.cachedCertificateCredentials.put(credential.name(), credential);
return ServicePrincipalImpl.this;
}))
.concatWith(
manager()
.inner()
.getServicePrincipals()
.listPasswordCredentialsAsync(id())
.map(
passwordCredentialInner -> {
PasswordCredential credential = new PasswordCredentialImpl<>(passwordCredentialInner);
ServicePrincipalImpl.this.cachedPasswordCredentials.put(credential.name(), credential);
return ServicePrincipalImpl.this;
}))
.last();
}
@Override
public Mono<ServicePrincipal> refreshAsync() {
return getInnerAsync().map(innerToFluentMap(this)).flatMap(application -> refreshCredentialsAsync());
}
@Override
public CertificateCredentialImpl<ServicePrincipalImpl> defineCertificateCredential(String name) {
return new CertificateCredentialImpl<>(name, this);
}
@Override
public PasswordCredentialImpl<ServicePrincipalImpl> definePasswordCredential(String name) {
return new PasswordCredentialImpl<>(name, this);
}
@Override
public ServicePrincipalImpl withoutCredential(String name) {
if (cachedPasswordCredentials.containsKey(name)) {
passwordCredentialsToDelete.add(name);
} else if (cachedCertificateCredentials.containsKey(name)) {
certificateCredentialsToDelete.add(name);
}
return this;
}
@Override
public ServicePrincipalImpl withCertificateCredential(CertificateCredentialImpl<?> credential) {
this.certificateCredentialsToCreate.add(credential);
return this;
}
@Override
public ServicePrincipalImpl withPasswordCredential(PasswordCredentialImpl<?> credential) {
this.passwordCredentialsToCreate.add(credential);
return this;
}
@Override
public ServicePrincipalImpl withExistingApplication(String id) {
createParameters.withAppId(id);
return this;
}
@Override
public ServicePrincipalImpl withExistingApplication(ActiveDirectoryApplication application) {
createParameters.withAppId(application.applicationId());
return this;
}
@Override
public ServicePrincipalImpl withNewApplication(Creatable<ActiveDirectoryApplication> applicationCreatable) {
this.addDependency(applicationCreatable);
this.applicationCreatable = applicationCreatable;
return this;
}
@Override
public ServicePrincipalImpl withNewApplication(String signOnUrl) {
return withNewApplication(
manager.applications().define(name()).withSignOnUrl(signOnUrl).withIdentifierUrl(signOnUrl));
}
@Override
public ServicePrincipalImpl withNewRole(BuiltInRole role, String scope) {
this.rolesToCreate.put(scope, role);
return this;
}
@Override
public ServicePrincipalImpl withNewRoleInSubscription(BuiltInRole role, String subscriptionId) {
this.assignedSubscription = subscriptionId;
return withNewRole(role, "subscriptions/" + subscriptionId);
}
@Override
public ServicePrincipalImpl withNewRoleInResourceGroup(BuiltInRole role, ResourceGroup resourceGroup) {
return withNewRole(role, resourceGroup.id());
}
@Override
public Update withoutRole(RoleAssignment roleAssignment) {
this.rolesToDelete.add(roleAssignment.id());
return this;
}
@Override
public String id() {
return inner().objectId();
}
@Override
public AuthorizationManager manager() {
return this.manager;
}
} | class ServicePrincipalImpl extends CreatableUpdatableImpl<ServicePrincipal, ServicePrincipalInner, ServicePrincipalImpl>
implements ServicePrincipal,
ServicePrincipal.Definition,
ServicePrincipal.Update,
HasCredential<ServicePrincipalImpl> {
private AuthorizationManager manager;
private Map<String, PasswordCredential> cachedPasswordCredentials;
private Map<String, CertificateCredential> cachedCertificateCredentials;
private Map<String, RoleAssignment> cachedRoleAssignments;
private ServicePrincipalCreateParameters createParameters;
private Creatable<ActiveDirectoryApplication> applicationCreatable;
private Map<String, BuiltInRole> rolesToCreate;
private Set<String> rolesToDelete;
String assignedSubscription;
private List<CertificateCredentialImpl<?>> certificateCredentialsToCreate;
private List<PasswordCredentialImpl<?>> passwordCredentialsToCreate;
private Set<String> certificateCredentialsToDelete;
private Set<String> passwordCredentialsToDelete;
ServicePrincipalImpl(ServicePrincipalInner innerObject, AuthorizationManager manager) {
super(innerObject.displayName(), innerObject);
this.manager = manager;
this.createParameters = new ServicePrincipalCreateParameters();
this.createParameters.withAccountEnabled(true);
this.cachedRoleAssignments = new HashMap<>();
this.rolesToCreate = new HashMap<>();
this.rolesToDelete = new HashSet<>();
this.cachedCertificateCredentials = new HashMap<>();
this.certificateCredentialsToCreate = new ArrayList<>();
this.certificateCredentialsToDelete = new HashSet<>();
this.cachedPasswordCredentials = new HashMap<>();
this.passwordCredentialsToCreate = new ArrayList<>();
this.passwordCredentialsToDelete = new HashSet<>();
}
@Override
public String applicationId() {
return inner().appId();
}
@Override
public List<String> servicePrincipalNames() {
return inner().servicePrincipalNames();
}
@Override
public Map<String, PasswordCredential> passwordCredentials() {
return Collections.unmodifiableMap(cachedPasswordCredentials);
}
@Override
public Map<String, CertificateCredential> certificateCredentials() {
return Collections.unmodifiableMap(cachedCertificateCredentials);
}
@Override
public Set<RoleAssignment> roleAssignments() {
return Collections.unmodifiableSet(new HashSet<>(cachedRoleAssignments.values()));
}
@Override
protected Mono<ServicePrincipalInner> getInnerAsync() {
return manager.inner().getServicePrincipals().getAsync(id());
}
@Override
public Mono<ServicePrincipal> createResourceAsync() {
Mono<ServicePrincipal> sp = Mono.just(this);
if (isInCreateMode()) {
if (applicationCreatable != null) {
ActiveDirectoryApplication application = this.taskResult(applicationCreatable.key());
createParameters.withAppId(application.applicationId());
}
sp = manager.inner().getServicePrincipals().createAsync(createParameters).map(innerToFluentMap(this));
}
return sp
.flatMap(
servicePrincipal ->
submitCredentialsAsync(servicePrincipal).mergeWith(submitRolesAsync(servicePrincipal)).last())
.map(
servicePrincipal -> {
for (PasswordCredentialImpl<?> passwordCredential : passwordCredentialsToCreate) {
passwordCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
}
for (CertificateCredentialImpl<?> certificateCredential : certificateCredentialsToCreate) {
certificateCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
}
passwordCredentialsToCreate.clear();
certificateCredentialsToCreate.clear();
return servicePrincipal;
});
}
private Mono<ServicePrincipal> submitCredentialsAsync(final ServicePrincipal sp) {
Mono<ServicePrincipal> mono = Mono.empty();
if (!certificateCredentialsToCreate.isEmpty() || !certificateCredentialsToDelete.isEmpty()) {
Map<String, CertificateCredential> newCerts = new HashMap<>(cachedCertificateCredentials);
for (String delete : certificateCredentialsToDelete) {
newCerts.remove(delete);
}
for (CertificateCredential create : certificateCredentialsToCreate) {
newCerts.put(create.name(), create);
}
List<KeyCredentialInner> updateKeyCredentials = new ArrayList<>();
for (CertificateCredential certificateCredential : newCerts.values()) {
updateKeyCredentials.add(certificateCredential.inner());
}
mono =
mono
.concatWith(
manager()
.inner()
.getServicePrincipals()
.updateKeyCredentialsAsync(sp.id(), updateKeyCredentials)
.then(Mono.just(ServicePrincipalImpl.this)))
.last();
}
if (!passwordCredentialsToCreate.isEmpty() || !passwordCredentialsToDelete.isEmpty()) {
Map<String, PasswordCredential> newPasses = new HashMap<>(cachedPasswordCredentials);
for (String delete : passwordCredentialsToDelete) {
newPasses.remove(delete);
}
for (PasswordCredential create : passwordCredentialsToCreate) {
newPasses.put(create.name(), create);
}
List<PasswordCredentialInner> updatePasswordCredentials = new ArrayList<>();
for (PasswordCredential passwordCredential : newPasses.values()) {
updatePasswordCredentials.add(passwordCredential.inner());
}
mono =
mono
.concatWith(
manager()
.inner()
.getServicePrincipals()
.updatePasswordCredentialsAsync(sp.id(), updatePasswordCredentials)
.then(Mono.just(ServicePrincipalImpl.this)))
.last();
}
return mono
.flatMap(
servicePrincipal -> {
passwordCredentialsToDelete.clear();
certificateCredentialsToDelete.clear();
return refreshCredentialsAsync();
});
}
@Override
public boolean isInCreateMode() {
return id() == null;
}
Mono<ServicePrincipal> refreshCredentialsAsync() {
return Mono
.just(ServicePrincipalImpl.this)
.map(
(Function<ServicePrincipalImpl, ServicePrincipal>)
servicePrincipal -> {
servicePrincipal.cachedCertificateCredentials.clear();
servicePrincipal.cachedPasswordCredentials.clear();
return servicePrincipal;
})
.concatWith(
manager()
.inner()
.getServicePrincipals()
.listKeyCredentialsAsync(id())
.map(
keyCredentialInner -> {
CertificateCredential credential = new CertificateCredentialImpl<>(keyCredentialInner);
ServicePrincipalImpl.this.cachedCertificateCredentials.put(credential.name(), credential);
return ServicePrincipalImpl.this;
}))
.concatWith(
manager()
.inner()
.getServicePrincipals()
.listPasswordCredentialsAsync(id())
.map(
passwordCredentialInner -> {
PasswordCredential credential = new PasswordCredentialImpl<>(passwordCredentialInner);
ServicePrincipalImpl.this.cachedPasswordCredentials.put(credential.name(), credential);
return ServicePrincipalImpl.this;
}))
.last();
}
@Override
public Mono<ServicePrincipal> refreshAsync() {
return getInnerAsync().map(innerToFluentMap(this)).flatMap(application -> refreshCredentialsAsync());
}
@Override
public CertificateCredentialImpl<ServicePrincipalImpl> defineCertificateCredential(String name) {
return new CertificateCredentialImpl<>(name, this);
}
@Override
public PasswordCredentialImpl<ServicePrincipalImpl> definePasswordCredential(String name) {
return new PasswordCredentialImpl<>(name, this);
}
@Override
public ServicePrincipalImpl withoutCredential(String name) {
if (cachedPasswordCredentials.containsKey(name)) {
passwordCredentialsToDelete.add(name);
} else if (cachedCertificateCredentials.containsKey(name)) {
certificateCredentialsToDelete.add(name);
}
return this;
}
@Override
public ServicePrincipalImpl withCertificateCredential(CertificateCredentialImpl<?> credential) {
this.certificateCredentialsToCreate.add(credential);
return this;
}
@Override
public ServicePrincipalImpl withPasswordCredential(PasswordCredentialImpl<?> credential) {
this.passwordCredentialsToCreate.add(credential);
return this;
}
@Override
public ServicePrincipalImpl withExistingApplication(String id) {
createParameters.withAppId(id);
return this;
}
@Override
public ServicePrincipalImpl withExistingApplication(ActiveDirectoryApplication application) {
createParameters.withAppId(application.applicationId());
return this;
}
@Override
public ServicePrincipalImpl withNewApplication(Creatable<ActiveDirectoryApplication> applicationCreatable) {
this.addDependency(applicationCreatable);
this.applicationCreatable = applicationCreatable;
return this;
}
@Override
public ServicePrincipalImpl withNewApplication(String signOnUrl) {
return withNewApplication(
manager.applications().define(name()).withSignOnUrl(signOnUrl).withIdentifierUrl(signOnUrl));
}
@Override
public ServicePrincipalImpl withNewRole(BuiltInRole role, String scope) {
this.rolesToCreate.put(scope, role);
return this;
}
@Override
public ServicePrincipalImpl withNewRoleInSubscription(BuiltInRole role, String subscriptionId) {
this.assignedSubscription = subscriptionId;
return withNewRole(role, "subscriptions/" + subscriptionId);
}
@Override
public ServicePrincipalImpl withNewRoleInResourceGroup(BuiltInRole role, ResourceGroup resourceGroup) {
return withNewRole(role, resourceGroup.id());
}
@Override
public Update withoutRole(RoleAssignment roleAssignment) {
this.rolesToDelete.add(roleAssignment.id());
return this;
}
@Override
public String id() {
return inner().objectId();
}
@Override
public AuthorizationManager manager() {
return this.manager;
}
} |
Likely this `if` is no longer needed? | public static boolean runSample(final Azure azure) {
final String suffix = ".azurewebsites.net";
final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20);
final String app2Name = azure.sdkContext().randomResourceName("webapp2-", 20);
final String app3Name = azure.sdkContext().randomResourceName("webapp3-", 20);
final String app4Name = azure.sdkContext().randomResourceName("webapp4-", 20);
final String app1Url = app1Name + suffix;
final String app2Url = app2Name + suffix;
final String app3Url = app3Name + suffix;
final String app4Url = app4Name + suffix;
final String planName = azure.sdkContext().randomResourceName("jplan_", 15);
final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24);
try {
System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
Flux<?> app1Observable = azure.webApps().define(app1Name)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.STANDARD_S1)
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync()
.flatMapMany(indexable -> {
if (indexable instanceof WebApp) {
WebApp app = indexable;
System.out.println("Created web app " + app.name());
return Flux.merge(
Flux.just(indexable),
app.getPublishingProfileAsync()
.map(publishingProfile -> {
System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
Utils.uploadFileViaFtp(publishingProfile,
"helloworld.war",
ManageWebAppSourceControlAsync.class.getResourceAsStream("/helloworld.war"));
System.out.println("Deployment helloworld.war to web app " + app1Name + " completed");
return publishingProfile;
}));
}
return Flux.just(indexable);
});
System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
System.out.println("Creating another web app " + app3Name + "...");
System.out.println("Creating another web app " + app4Name + "...");
Flux<?> app234Observable = azure.appServicePlans()
.getByResourceGroupAsync(rgName, planName)
.flatMapMany(plan -> {
return Flux.merge(
azure.webApps().define(app2Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.withLocalGitSourceControl()
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync(),
azure.webApps().define(app3Name)
.withExistingWindowsPlan(plan)
.withNewResourceGroup(rgName)
.defineSourceControl()
.withPublicGitRepository(
"https:
.withBranch("master")
.attach()
.createAsync(),
azure.webApps()
.define(app4Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.createAsync());
}).flatMap(indexable -> {
if (indexable instanceof WebApp) {
WebApp app = indexable;
System.out.println("Created web app " + app.name());
if (!app.name().equals(app2Name)) {
return Flux.just(indexable);
}
return app.getPublishingProfileAsync()
.map(profile -> {
System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
Git git = null;
try {
git = Git
.init()
.setDirectory(new File(
ManageWebAppSourceControlAsync.class.getResource(
"/azure-samples-appservice-helloworld/")
.getPath()))
.call();
git.add().addFilepattern(".").call();
git.commit().setMessage("Initial commit").call();
PushCommand command = git.push();
command.setRemote(profile.gitUrl());
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
command.setRefSpecs(new RefSpec("master:master"));
command.setForce(true);
command.call();
} catch (GitAPIException e) {
e.printStackTrace();
}
System.out.println("Deployment to web app " + app2Name + " completed");
return profile;
});
}
return Flux.just(indexable);
});
Flux.merge(app1Observable, app234Observable).blockLast();
System.out.println("Warming up " + app1Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app2Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app3Url + "...");
Utils.curl("http:
System.out.println("Warming up " + app4Url + "...");
Utils.curl("http:
SdkContext.sleep(5000);
System.out.println("CURLing " + app1Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app2Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app3Url + "...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app4Url + "...");
System.out.println(Utils.curl("http:
return true;
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
} | if (indexable instanceof WebApp) { | public static boolean runSample(final Azure azure) {
final String suffix = ".azurewebsites.net";
final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20);
final String app2Name = azure.sdkContext().randomResourceName("webapp2-", 20);
final String app3Name = azure.sdkContext().randomResourceName("webapp3-", 20);
final String app4Name = azure.sdkContext().randomResourceName("webapp4-", 20);
final String app1Url = app1Name + suffix;
final String app2Url = app2Name + suffix;
final String app3Url = app3Name + suffix;
final String app4Url = app4Name + suffix;
final String planName = azure.sdkContext().randomResourceName("jplan_", 15);
final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24);
try {
System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
Flux<?> app1Observable = azure.webApps().define(app1Name)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.STANDARD_S1)
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync()
.flatMapMany(app -> {
System.out.println("Created web app " + app.name());
return Flux.merge(
Flux.just(app),
app.getPublishingProfileAsync()
.map(publishingProfile -> {
System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
Utils.uploadFileViaFtp(publishingProfile,
"helloworld.war",
ManageWebAppSourceControlAsync.class.getResourceAsStream("/helloworld.war"));
System.out.println("Deployment helloworld.war to web app " + app1Name + " completed");
return publishingProfile;
}));
});
System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
System.out.println("Creating another web app " + app3Name + "...");
System.out.println("Creating another web app " + app4Name + "...");
Flux<?> app234Observable = azure.appServicePlans()
.getByResourceGroupAsync(rgName, planName)
.flatMapMany(plan -> {
return Flux.merge(
azure.webApps().define(app2Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.withLocalGitSourceControl()
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync(),
azure.webApps().define(app3Name)
.withExistingWindowsPlan(plan)
.withNewResourceGroup(rgName)
.defineSourceControl()
.withPublicGitRepository(
"https:
.withBranch("master")
.attach()
.createAsync(),
azure.webApps()
.define(app4Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.createAsync());
}).flatMap(app -> {
System.out.println("Created web app " + app.name());
if (!app.name().equals(app2Name)) {
return Flux.just(app);
}
return app.getPublishingProfileAsync()
.map(profile -> {
System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
Git git = null;
try {
git = Git
.init()
.setDirectory(new File(
ManageWebAppSourceControlAsync.class.getResource(
"/azure-samples-appservice-helloworld/")
.getPath()))
.call();
git.add().addFilepattern(".").call();
git.commit().setMessage("Initial commit").call();
PushCommand command = git.push();
command.setRemote(profile.gitUrl());
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
command.setRefSpecs(new RefSpec("master:master"));
command.setForce(true);
command.call();
} catch (GitAPIException e) {
e.printStackTrace();
}
System.out.println("Deployment to web app " + app2Name + " completed");
return profile;
});
});
Flux.merge(app1Observable, app234Observable).blockLast();
System.out.println("Warming up " + app1Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app2Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app3Url + "...");
Utils.curl("http:
System.out.println("Warming up " + app4Url + "...");
Utils.curl("http:
SdkContext.sleep(5000);
System.out.println("CURLing " + app1Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app2Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app3Url + "...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app4Url + "...");
System.out.println(Utils.curl("http:
return true;
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
} | class ManageWebAppSourceControlAsync {
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential = new DefaultAzureCredentialBuilder()
.build();
Azure azure = Azure
.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
System.out.println("Selected subscription: " + azure.subscriptionId());
runSample(azure);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} | class ManageWebAppSourceControlAsync {
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential = new DefaultAzureCredentialBuilder()
.build();
Azure azure = Azure
.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
System.out.println("Selected subscription: " + azure.subscriptionId());
runSample(azure);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} |
Yes, there are lots of `if` not needed, but I don't want to change so much. | public static boolean runSample(final Azure azure) {
final String suffix = ".azurewebsites.net";
final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20);
final String app2Name = azure.sdkContext().randomResourceName("webapp2-", 20);
final String app3Name = azure.sdkContext().randomResourceName("webapp3-", 20);
final String app4Name = azure.sdkContext().randomResourceName("webapp4-", 20);
final String app1Url = app1Name + suffix;
final String app2Url = app2Name + suffix;
final String app3Url = app3Name + suffix;
final String app4Url = app4Name + suffix;
final String planName = azure.sdkContext().randomResourceName("jplan_", 15);
final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24);
try {
System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
Flux<?> app1Observable = azure.webApps().define(app1Name)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.STANDARD_S1)
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync()
.flatMapMany(indexable -> {
if (indexable instanceof WebApp) {
WebApp app = indexable;
System.out.println("Created web app " + app.name());
return Flux.merge(
Flux.just(indexable),
app.getPublishingProfileAsync()
.map(publishingProfile -> {
System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
Utils.uploadFileViaFtp(publishingProfile,
"helloworld.war",
ManageWebAppSourceControlAsync.class.getResourceAsStream("/helloworld.war"));
System.out.println("Deployment helloworld.war to web app " + app1Name + " completed");
return publishingProfile;
}));
}
return Flux.just(indexable);
});
System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
System.out.println("Creating another web app " + app3Name + "...");
System.out.println("Creating another web app " + app4Name + "...");
Flux<?> app234Observable = azure.appServicePlans()
.getByResourceGroupAsync(rgName, planName)
.flatMapMany(plan -> {
return Flux.merge(
azure.webApps().define(app2Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.withLocalGitSourceControl()
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync(),
azure.webApps().define(app3Name)
.withExistingWindowsPlan(plan)
.withNewResourceGroup(rgName)
.defineSourceControl()
.withPublicGitRepository(
"https:
.withBranch("master")
.attach()
.createAsync(),
azure.webApps()
.define(app4Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.createAsync());
}).flatMap(indexable -> {
if (indexable instanceof WebApp) {
WebApp app = indexable;
System.out.println("Created web app " + app.name());
if (!app.name().equals(app2Name)) {
return Flux.just(indexable);
}
return app.getPublishingProfileAsync()
.map(profile -> {
System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
Git git = null;
try {
git = Git
.init()
.setDirectory(new File(
ManageWebAppSourceControlAsync.class.getResource(
"/azure-samples-appservice-helloworld/")
.getPath()))
.call();
git.add().addFilepattern(".").call();
git.commit().setMessage("Initial commit").call();
PushCommand command = git.push();
command.setRemote(profile.gitUrl());
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
command.setRefSpecs(new RefSpec("master:master"));
command.setForce(true);
command.call();
} catch (GitAPIException e) {
e.printStackTrace();
}
System.out.println("Deployment to web app " + app2Name + " completed");
return profile;
});
}
return Flux.just(indexable);
});
Flux.merge(app1Observable, app234Observable).blockLast();
System.out.println("Warming up " + app1Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app2Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app3Url + "...");
Utils.curl("http:
System.out.println("Warming up " + app4Url + "...");
Utils.curl("http:
SdkContext.sleep(5000);
System.out.println("CURLing " + app1Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app2Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app3Url + "...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app4Url + "...");
System.out.println(Utils.curl("http:
return true;
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
} | if (indexable instanceof WebApp) { | public static boolean runSample(final Azure azure) {
final String suffix = ".azurewebsites.net";
final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20);
final String app2Name = azure.sdkContext().randomResourceName("webapp2-", 20);
final String app3Name = azure.sdkContext().randomResourceName("webapp3-", 20);
final String app4Name = azure.sdkContext().randomResourceName("webapp4-", 20);
final String app1Url = app1Name + suffix;
final String app2Url = app2Name + suffix;
final String app3Url = app3Name + suffix;
final String app4Url = app4Name + suffix;
final String planName = azure.sdkContext().randomResourceName("jplan_", 15);
final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24);
try {
System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
Flux<?> app1Observable = azure.webApps().define(app1Name)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.STANDARD_S1)
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync()
.flatMapMany(app -> {
System.out.println("Created web app " + app.name());
return Flux.merge(
Flux.just(app),
app.getPublishingProfileAsync()
.map(publishingProfile -> {
System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
Utils.uploadFileViaFtp(publishingProfile,
"helloworld.war",
ManageWebAppSourceControlAsync.class.getResourceAsStream("/helloworld.war"));
System.out.println("Deployment helloworld.war to web app " + app1Name + " completed");
return publishingProfile;
}));
});
System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
System.out.println("Creating another web app " + app3Name + "...");
System.out.println("Creating another web app " + app4Name + "...");
Flux<?> app234Observable = azure.appServicePlans()
.getByResourceGroupAsync(rgName, planName)
.flatMapMany(plan -> {
return Flux.merge(
azure.webApps().define(app2Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.withLocalGitSourceControl()
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync(),
azure.webApps().define(app3Name)
.withExistingWindowsPlan(plan)
.withNewResourceGroup(rgName)
.defineSourceControl()
.withPublicGitRepository(
"https:
.withBranch("master")
.attach()
.createAsync(),
azure.webApps()
.define(app4Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.createAsync());
}).flatMap(app -> {
System.out.println("Created web app " + app.name());
if (!app.name().equals(app2Name)) {
return Flux.just(app);
}
return app.getPublishingProfileAsync()
.map(profile -> {
System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
Git git = null;
try {
git = Git
.init()
.setDirectory(new File(
ManageWebAppSourceControlAsync.class.getResource(
"/azure-samples-appservice-helloworld/")
.getPath()))
.call();
git.add().addFilepattern(".").call();
git.commit().setMessage("Initial commit").call();
PushCommand command = git.push();
command.setRemote(profile.gitUrl());
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
command.setRefSpecs(new RefSpec("master:master"));
command.setForce(true);
command.call();
} catch (GitAPIException e) {
e.printStackTrace();
}
System.out.println("Deployment to web app " + app2Name + " completed");
return profile;
});
});
Flux.merge(app1Observable, app234Observable).blockLast();
System.out.println("Warming up " + app1Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app2Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app3Url + "...");
Utils.curl("http:
System.out.println("Warming up " + app4Url + "...");
Utils.curl("http:
SdkContext.sleep(5000);
System.out.println("CURLing " + app1Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app2Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app3Url + "...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app4Url + "...");
System.out.println(Utils.curl("http:
return true;
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
} | class ManageWebAppSourceControlAsync {
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential = new DefaultAzureCredentialBuilder()
.build();
Azure azure = Azure
.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
System.out.println("Selected subscription: " + azure.subscriptionId());
runSample(azure);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} | class ManageWebAppSourceControlAsync {
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential = new DefaultAzureCredentialBuilder()
.build();
Azure azure = Azure
.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
System.out.println("Selected subscription: " + azure.subscriptionId());
runSample(azure);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} |
done | private Mono<ServicePrincipal> submitRolesAsync(final ServicePrincipal servicePrincipal) {
Mono<ServicePrincipal> create;
if (rolesToCreate.isEmpty()) {
create = Mono.just(servicePrincipal);
} else {
create =
Flux
.fromIterable(rolesToCreate.entrySet())
.flatMap(
roleEntry ->
manager()
.roleAssignments()
.define(this.manager().sdkContext().randomUuid())
.forServicePrincipal(servicePrincipal)
.withBuiltInRole(roleEntry.getValue())
.withScope(roleEntry.getKey())
.createAsync())
.doOnNext(
indexable ->
cachedRoleAssignments.put((indexable).id(), indexable))
.last()
.map(
indexable -> {
rolesToCreate.clear();
return servicePrincipal;
});
}
Mono<ServicePrincipal> delete;
if (rolesToDelete.isEmpty()) {
delete = Mono.just(servicePrincipal);
} else {
delete =
Flux
.fromIterable(rolesToDelete)
.flatMap(
role ->
manager()
.roleAssignments()
.deleteByIdAsync(cachedRoleAssignments.get(role).id())
.thenReturn(role))
.doOnNext(s -> cachedRoleAssignments.remove(s))
.last()
.map(
s -> {
rolesToDelete.clear();
return servicePrincipal;
});
}
return create.mergeWith(delete).last();
} | cachedRoleAssignments.put((indexable).id(), indexable)) | private Mono<ServicePrincipal> submitRolesAsync(final ServicePrincipal servicePrincipal) {
Mono<ServicePrincipal> create;
if (rolesToCreate.isEmpty()) {
create = Mono.just(servicePrincipal);
} else {
create =
Flux
.fromIterable(rolesToCreate.entrySet())
.flatMap(
roleEntry ->
manager()
.roleAssignments()
.define(this.manager().sdkContext().randomUuid())
.forServicePrincipal(servicePrincipal)
.withBuiltInRole(roleEntry.getValue())
.withScope(roleEntry.getKey())
.createAsync())
.doOnNext(
indexable ->
cachedRoleAssignments.put(indexable.id(), indexable))
.last()
.map(
indexable -> {
rolesToCreate.clear();
return servicePrincipal;
});
}
Mono<ServicePrincipal> delete;
if (rolesToDelete.isEmpty()) {
delete = Mono.just(servicePrincipal);
} else {
delete =
Flux
.fromIterable(rolesToDelete)
.flatMap(
role ->
manager()
.roleAssignments()
.deleteByIdAsync(cachedRoleAssignments.get(role).id())
.thenReturn(role))
.doOnNext(s -> cachedRoleAssignments.remove(s))
.last()
.map(
s -> {
rolesToDelete.clear();
return servicePrincipal;
});
}
return create.mergeWith(delete).last();
} | class ServicePrincipalImpl extends CreatableUpdatableImpl<ServicePrincipal, ServicePrincipalInner, ServicePrincipalImpl>
implements ServicePrincipal,
ServicePrincipal.Definition,
ServicePrincipal.Update,
HasCredential<ServicePrincipalImpl> {
private AuthorizationManager manager;
private Map<String, PasswordCredential> cachedPasswordCredentials;
private Map<String, CertificateCredential> cachedCertificateCredentials;
private Map<String, RoleAssignment> cachedRoleAssignments;
private ServicePrincipalCreateParameters createParameters;
private Creatable<ActiveDirectoryApplication> applicationCreatable;
private Map<String, BuiltInRole> rolesToCreate;
private Set<String> rolesToDelete;
String assignedSubscription;
private List<CertificateCredentialImpl<?>> certificateCredentialsToCreate;
private List<PasswordCredentialImpl<?>> passwordCredentialsToCreate;
private Set<String> certificateCredentialsToDelete;
private Set<String> passwordCredentialsToDelete;
ServicePrincipalImpl(ServicePrincipalInner innerObject, AuthorizationManager manager) {
super(innerObject.displayName(), innerObject);
this.manager = manager;
this.createParameters = new ServicePrincipalCreateParameters();
this.createParameters.withAccountEnabled(true);
this.cachedRoleAssignments = new HashMap<>();
this.rolesToCreate = new HashMap<>();
this.rolesToDelete = new HashSet<>();
this.cachedCertificateCredentials = new HashMap<>();
this.certificateCredentialsToCreate = new ArrayList<>();
this.certificateCredentialsToDelete = new HashSet<>();
this.cachedPasswordCredentials = new HashMap<>();
this.passwordCredentialsToCreate = new ArrayList<>();
this.passwordCredentialsToDelete = new HashSet<>();
}
@Override
public String applicationId() {
return inner().appId();
}
@Override
public List<String> servicePrincipalNames() {
return inner().servicePrincipalNames();
}
@Override
public Map<String, PasswordCredential> passwordCredentials() {
return Collections.unmodifiableMap(cachedPasswordCredentials);
}
@Override
public Map<String, CertificateCredential> certificateCredentials() {
return Collections.unmodifiableMap(cachedCertificateCredentials);
}
@Override
public Set<RoleAssignment> roleAssignments() {
return Collections.unmodifiableSet(new HashSet<>(cachedRoleAssignments.values()));
}
@Override
protected Mono<ServicePrincipalInner> getInnerAsync() {
return manager.inner().getServicePrincipals().getAsync(id());
}
@Override
public Mono<ServicePrincipal> createResourceAsync() {
Mono<ServicePrincipal> sp = Mono.just(this);
if (isInCreateMode()) {
if (applicationCreatable != null) {
ActiveDirectoryApplication application = this.taskResult(applicationCreatable.key());
createParameters.withAppId(application.applicationId());
}
sp = manager.inner().getServicePrincipals().createAsync(createParameters).map(innerToFluentMap(this));
}
return sp
.flatMap(
servicePrincipal ->
submitCredentialsAsync(servicePrincipal).mergeWith(submitRolesAsync(servicePrincipal)).last())
.map(
servicePrincipal -> {
for (PasswordCredentialImpl<?> passwordCredential : passwordCredentialsToCreate) {
passwordCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
}
for (CertificateCredentialImpl<?> certificateCredential : certificateCredentialsToCreate) {
certificateCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
}
passwordCredentialsToCreate.clear();
certificateCredentialsToCreate.clear();
return servicePrincipal;
});
}
private Mono<ServicePrincipal> submitCredentialsAsync(final ServicePrincipal sp) {
Mono<ServicePrincipal> mono = Mono.empty();
if (!certificateCredentialsToCreate.isEmpty() || !certificateCredentialsToDelete.isEmpty()) {
Map<String, CertificateCredential> newCerts = new HashMap<>(cachedCertificateCredentials);
for (String delete : certificateCredentialsToDelete) {
newCerts.remove(delete);
}
for (CertificateCredential create : certificateCredentialsToCreate) {
newCerts.put(create.name(), create);
}
List<KeyCredentialInner> updateKeyCredentials = new ArrayList<>();
for (CertificateCredential certificateCredential : newCerts.values()) {
updateKeyCredentials.add(certificateCredential.inner());
}
mono =
mono
.concatWith(
manager()
.inner()
.getServicePrincipals()
.updateKeyCredentialsAsync(sp.id(), updateKeyCredentials)
.then(Mono.just(ServicePrincipalImpl.this)))
.last();
}
if (!passwordCredentialsToCreate.isEmpty() || !passwordCredentialsToDelete.isEmpty()) {
Map<String, PasswordCredential> newPasses = new HashMap<>(cachedPasswordCredentials);
for (String delete : passwordCredentialsToDelete) {
newPasses.remove(delete);
}
for (PasswordCredential create : passwordCredentialsToCreate) {
newPasses.put(create.name(), create);
}
List<PasswordCredentialInner> updatePasswordCredentials = new ArrayList<>();
for (PasswordCredential passwordCredential : newPasses.values()) {
updatePasswordCredentials.add(passwordCredential.inner());
}
mono =
mono
.concatWith(
manager()
.inner()
.getServicePrincipals()
.updatePasswordCredentialsAsync(sp.id(), updatePasswordCredentials)
.then(Mono.just(ServicePrincipalImpl.this)))
.last();
}
return mono
.flatMap(
servicePrincipal -> {
passwordCredentialsToDelete.clear();
certificateCredentialsToDelete.clear();
return refreshCredentialsAsync();
});
}
@Override
public boolean isInCreateMode() {
return id() == null;
}
Mono<ServicePrincipal> refreshCredentialsAsync() {
return Mono
.just(ServicePrincipalImpl.this)
.map(
(Function<ServicePrincipalImpl, ServicePrincipal>)
servicePrincipal -> {
servicePrincipal.cachedCertificateCredentials.clear();
servicePrincipal.cachedPasswordCredentials.clear();
return servicePrincipal;
})
.concatWith(
manager()
.inner()
.getServicePrincipals()
.listKeyCredentialsAsync(id())
.map(
keyCredentialInner -> {
CertificateCredential credential = new CertificateCredentialImpl<>(keyCredentialInner);
ServicePrincipalImpl.this.cachedCertificateCredentials.put(credential.name(), credential);
return ServicePrincipalImpl.this;
}))
.concatWith(
manager()
.inner()
.getServicePrincipals()
.listPasswordCredentialsAsync(id())
.map(
passwordCredentialInner -> {
PasswordCredential credential = new PasswordCredentialImpl<>(passwordCredentialInner);
ServicePrincipalImpl.this.cachedPasswordCredentials.put(credential.name(), credential);
return ServicePrincipalImpl.this;
}))
.last();
}
@Override
public Mono<ServicePrincipal> refreshAsync() {
return getInnerAsync().map(innerToFluentMap(this)).flatMap(application -> refreshCredentialsAsync());
}
@Override
public CertificateCredentialImpl<ServicePrincipalImpl> defineCertificateCredential(String name) {
return new CertificateCredentialImpl<>(name, this);
}
@Override
public PasswordCredentialImpl<ServicePrincipalImpl> definePasswordCredential(String name) {
return new PasswordCredentialImpl<>(name, this);
}
@Override
public ServicePrincipalImpl withoutCredential(String name) {
if (cachedPasswordCredentials.containsKey(name)) {
passwordCredentialsToDelete.add(name);
} else if (cachedCertificateCredentials.containsKey(name)) {
certificateCredentialsToDelete.add(name);
}
return this;
}
@Override
public ServicePrincipalImpl withCertificateCredential(CertificateCredentialImpl<?> credential) {
this.certificateCredentialsToCreate.add(credential);
return this;
}
@Override
public ServicePrincipalImpl withPasswordCredential(PasswordCredentialImpl<?> credential) {
this.passwordCredentialsToCreate.add(credential);
return this;
}
@Override
public ServicePrincipalImpl withExistingApplication(String id) {
createParameters.withAppId(id);
return this;
}
@Override
public ServicePrincipalImpl withExistingApplication(ActiveDirectoryApplication application) {
createParameters.withAppId(application.applicationId());
return this;
}
@Override
public ServicePrincipalImpl withNewApplication(Creatable<ActiveDirectoryApplication> applicationCreatable) {
this.addDependency(applicationCreatable);
this.applicationCreatable = applicationCreatable;
return this;
}
@Override
public ServicePrincipalImpl withNewApplication(String signOnUrl) {
return withNewApplication(
manager.applications().define(name()).withSignOnUrl(signOnUrl).withIdentifierUrl(signOnUrl));
}
@Override
public ServicePrincipalImpl withNewRole(BuiltInRole role, String scope) {
this.rolesToCreate.put(scope, role);
return this;
}
@Override
public ServicePrincipalImpl withNewRoleInSubscription(BuiltInRole role, String subscriptionId) {
this.assignedSubscription = subscriptionId;
return withNewRole(role, "subscriptions/" + subscriptionId);
}
@Override
public ServicePrincipalImpl withNewRoleInResourceGroup(BuiltInRole role, ResourceGroup resourceGroup) {
return withNewRole(role, resourceGroup.id());
}
@Override
public Update withoutRole(RoleAssignment roleAssignment) {
this.rolesToDelete.add(roleAssignment.id());
return this;
}
@Override
public String id() {
return inner().objectId();
}
@Override
public AuthorizationManager manager() {
return this.manager;
}
} | class ServicePrincipalImpl extends CreatableUpdatableImpl<ServicePrincipal, ServicePrincipalInner, ServicePrincipalImpl>
implements ServicePrincipal,
ServicePrincipal.Definition,
ServicePrincipal.Update,
HasCredential<ServicePrincipalImpl> {
private AuthorizationManager manager;
private Map<String, PasswordCredential> cachedPasswordCredentials;
private Map<String, CertificateCredential> cachedCertificateCredentials;
private Map<String, RoleAssignment> cachedRoleAssignments;
private ServicePrincipalCreateParameters createParameters;
private Creatable<ActiveDirectoryApplication> applicationCreatable;
private Map<String, BuiltInRole> rolesToCreate;
private Set<String> rolesToDelete;
String assignedSubscription;
private List<CertificateCredentialImpl<?>> certificateCredentialsToCreate;
private List<PasswordCredentialImpl<?>> passwordCredentialsToCreate;
private Set<String> certificateCredentialsToDelete;
private Set<String> passwordCredentialsToDelete;
ServicePrincipalImpl(ServicePrincipalInner innerObject, AuthorizationManager manager) {
super(innerObject.displayName(), innerObject);
this.manager = manager;
this.createParameters = new ServicePrincipalCreateParameters();
this.createParameters.withAccountEnabled(true);
this.cachedRoleAssignments = new HashMap<>();
this.rolesToCreate = new HashMap<>();
this.rolesToDelete = new HashSet<>();
this.cachedCertificateCredentials = new HashMap<>();
this.certificateCredentialsToCreate = new ArrayList<>();
this.certificateCredentialsToDelete = new HashSet<>();
this.cachedPasswordCredentials = new HashMap<>();
this.passwordCredentialsToCreate = new ArrayList<>();
this.passwordCredentialsToDelete = new HashSet<>();
}
@Override
public String applicationId() {
return inner().appId();
}
@Override
public List<String> servicePrincipalNames() {
return inner().servicePrincipalNames();
}
@Override
public Map<String, PasswordCredential> passwordCredentials() {
return Collections.unmodifiableMap(cachedPasswordCredentials);
}
@Override
public Map<String, CertificateCredential> certificateCredentials() {
return Collections.unmodifiableMap(cachedCertificateCredentials);
}
@Override
public Set<RoleAssignment> roleAssignments() {
return Collections.unmodifiableSet(new HashSet<>(cachedRoleAssignments.values()));
}
@Override
protected Mono<ServicePrincipalInner> getInnerAsync() {
return manager.inner().getServicePrincipals().getAsync(id());
}
@Override
public Mono<ServicePrincipal> createResourceAsync() {
Mono<ServicePrincipal> sp = Mono.just(this);
if (isInCreateMode()) {
if (applicationCreatable != null) {
ActiveDirectoryApplication application = this.taskResult(applicationCreatable.key());
createParameters.withAppId(application.applicationId());
}
sp = manager.inner().getServicePrincipals().createAsync(createParameters).map(innerToFluentMap(this));
}
return sp
.flatMap(
servicePrincipal ->
submitCredentialsAsync(servicePrincipal).mergeWith(submitRolesAsync(servicePrincipal)).last())
.map(
servicePrincipal -> {
for (PasswordCredentialImpl<?> passwordCredential : passwordCredentialsToCreate) {
passwordCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
}
for (CertificateCredentialImpl<?> certificateCredential : certificateCredentialsToCreate) {
certificateCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
}
passwordCredentialsToCreate.clear();
certificateCredentialsToCreate.clear();
return servicePrincipal;
});
}
private Mono<ServicePrincipal> submitCredentialsAsync(final ServicePrincipal sp) {
Mono<ServicePrincipal> mono = Mono.empty();
if (!certificateCredentialsToCreate.isEmpty() || !certificateCredentialsToDelete.isEmpty()) {
Map<String, CertificateCredential> newCerts = new HashMap<>(cachedCertificateCredentials);
for (String delete : certificateCredentialsToDelete) {
newCerts.remove(delete);
}
for (CertificateCredential create : certificateCredentialsToCreate) {
newCerts.put(create.name(), create);
}
List<KeyCredentialInner> updateKeyCredentials = new ArrayList<>();
for (CertificateCredential certificateCredential : newCerts.values()) {
updateKeyCredentials.add(certificateCredential.inner());
}
mono =
mono
.concatWith(
manager()
.inner()
.getServicePrincipals()
.updateKeyCredentialsAsync(sp.id(), updateKeyCredentials)
.then(Mono.just(ServicePrincipalImpl.this)))
.last();
}
if (!passwordCredentialsToCreate.isEmpty() || !passwordCredentialsToDelete.isEmpty()) {
Map<String, PasswordCredential> newPasses = new HashMap<>(cachedPasswordCredentials);
for (String delete : passwordCredentialsToDelete) {
newPasses.remove(delete);
}
for (PasswordCredential create : passwordCredentialsToCreate) {
newPasses.put(create.name(), create);
}
List<PasswordCredentialInner> updatePasswordCredentials = new ArrayList<>();
for (PasswordCredential passwordCredential : newPasses.values()) {
updatePasswordCredentials.add(passwordCredential.inner());
}
mono =
mono
.concatWith(
manager()
.inner()
.getServicePrincipals()
.updatePasswordCredentialsAsync(sp.id(), updatePasswordCredentials)
.then(Mono.just(ServicePrincipalImpl.this)))
.last();
}
return mono
.flatMap(
servicePrincipal -> {
passwordCredentialsToDelete.clear();
certificateCredentialsToDelete.clear();
return refreshCredentialsAsync();
});
}
@Override
public boolean isInCreateMode() {
return id() == null;
}
Mono<ServicePrincipal> refreshCredentialsAsync() {
return Mono
.just(ServicePrincipalImpl.this)
.map(
(Function<ServicePrincipalImpl, ServicePrincipal>)
servicePrincipal -> {
servicePrincipal.cachedCertificateCredentials.clear();
servicePrincipal.cachedPasswordCredentials.clear();
return servicePrincipal;
})
.concatWith(
manager()
.inner()
.getServicePrincipals()
.listKeyCredentialsAsync(id())
.map(
keyCredentialInner -> {
CertificateCredential credential = new CertificateCredentialImpl<>(keyCredentialInner);
ServicePrincipalImpl.this.cachedCertificateCredentials.put(credential.name(), credential);
return ServicePrincipalImpl.this;
}))
.concatWith(
manager()
.inner()
.getServicePrincipals()
.listPasswordCredentialsAsync(id())
.map(
passwordCredentialInner -> {
PasswordCredential credential = new PasswordCredentialImpl<>(passwordCredentialInner);
ServicePrincipalImpl.this.cachedPasswordCredentials.put(credential.name(), credential);
return ServicePrincipalImpl.this;
}))
.last();
}
@Override
public Mono<ServicePrincipal> refreshAsync() {
return getInnerAsync().map(innerToFluentMap(this)).flatMap(application -> refreshCredentialsAsync());
}
@Override
public CertificateCredentialImpl<ServicePrincipalImpl> defineCertificateCredential(String name) {
return new CertificateCredentialImpl<>(name, this);
}
@Override
public PasswordCredentialImpl<ServicePrincipalImpl> definePasswordCredential(String name) {
return new PasswordCredentialImpl<>(name, this);
}
@Override
public ServicePrincipalImpl withoutCredential(String name) {
if (cachedPasswordCredentials.containsKey(name)) {
passwordCredentialsToDelete.add(name);
} else if (cachedCertificateCredentials.containsKey(name)) {
certificateCredentialsToDelete.add(name);
}
return this;
}
@Override
public ServicePrincipalImpl withCertificateCredential(CertificateCredentialImpl<?> credential) {
this.certificateCredentialsToCreate.add(credential);
return this;
}
@Override
public ServicePrincipalImpl withPasswordCredential(PasswordCredentialImpl<?> credential) {
this.passwordCredentialsToCreate.add(credential);
return this;
}
@Override
public ServicePrincipalImpl withExistingApplication(String id) {
createParameters.withAppId(id);
return this;
}
@Override
public ServicePrincipalImpl withExistingApplication(ActiveDirectoryApplication application) {
createParameters.withAppId(application.applicationId());
return this;
}
@Override
public ServicePrincipalImpl withNewApplication(Creatable<ActiveDirectoryApplication> applicationCreatable) {
this.addDependency(applicationCreatable);
this.applicationCreatable = applicationCreatable;
return this;
}
@Override
public ServicePrincipalImpl withNewApplication(String signOnUrl) {
return withNewApplication(
manager.applications().define(name()).withSignOnUrl(signOnUrl).withIdentifierUrl(signOnUrl));
}
@Override
public ServicePrincipalImpl withNewRole(BuiltInRole role, String scope) {
this.rolesToCreate.put(scope, role);
return this;
}
@Override
public ServicePrincipalImpl withNewRoleInSubscription(BuiltInRole role, String subscriptionId) {
this.assignedSubscription = subscriptionId;
return withNewRole(role, "subscriptions/" + subscriptionId);
}
@Override
public ServicePrincipalImpl withNewRoleInResourceGroup(BuiltInRole role, ResourceGroup resourceGroup) {
return withNewRole(role, resourceGroup.id());
}
@Override
public Update withoutRole(RoleAssignment roleAssignment) {
this.rolesToDelete.add(roleAssignment.id());
return this;
}
@Override
public String id() {
return inner().objectId();
}
@Override
public AuthorizationManager manager() {
return this.manager;
}
} |
fixed, it cause spotbugs error | public static boolean runSample(final Azure azure) {
final String suffix = ".azurewebsites.net";
final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20);
final String app2Name = azure.sdkContext().randomResourceName("webapp2-", 20);
final String app3Name = azure.sdkContext().randomResourceName("webapp3-", 20);
final String app4Name = azure.sdkContext().randomResourceName("webapp4-", 20);
final String app1Url = app1Name + suffix;
final String app2Url = app2Name + suffix;
final String app3Url = app3Name + suffix;
final String app4Url = app4Name + suffix;
final String planName = azure.sdkContext().randomResourceName("jplan_", 15);
final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24);
try {
System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
Flux<?> app1Observable = azure.webApps().define(app1Name)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.STANDARD_S1)
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync()
.flatMapMany(indexable -> {
if (indexable instanceof WebApp) {
WebApp app = indexable;
System.out.println("Created web app " + app.name());
return Flux.merge(
Flux.just(indexable),
app.getPublishingProfileAsync()
.map(publishingProfile -> {
System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
Utils.uploadFileViaFtp(publishingProfile,
"helloworld.war",
ManageWebAppSourceControlAsync.class.getResourceAsStream("/helloworld.war"));
System.out.println("Deployment helloworld.war to web app " + app1Name + " completed");
return publishingProfile;
}));
}
return Flux.just(indexable);
});
System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
System.out.println("Creating another web app " + app3Name + "...");
System.out.println("Creating another web app " + app4Name + "...");
Flux<?> app234Observable = azure.appServicePlans()
.getByResourceGroupAsync(rgName, planName)
.flatMapMany(plan -> {
return Flux.merge(
azure.webApps().define(app2Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.withLocalGitSourceControl()
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync(),
azure.webApps().define(app3Name)
.withExistingWindowsPlan(plan)
.withNewResourceGroup(rgName)
.defineSourceControl()
.withPublicGitRepository(
"https:
.withBranch("master")
.attach()
.createAsync(),
azure.webApps()
.define(app4Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.createAsync());
}).flatMap(indexable -> {
if (indexable instanceof WebApp) {
WebApp app = indexable;
System.out.println("Created web app " + app.name());
if (!app.name().equals(app2Name)) {
return Flux.just(indexable);
}
return app.getPublishingProfileAsync()
.map(profile -> {
System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
Git git = null;
try {
git = Git
.init()
.setDirectory(new File(
ManageWebAppSourceControlAsync.class.getResource(
"/azure-samples-appservice-helloworld/")
.getPath()))
.call();
git.add().addFilepattern(".").call();
git.commit().setMessage("Initial commit").call();
PushCommand command = git.push();
command.setRemote(profile.gitUrl());
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
command.setRefSpecs(new RefSpec("master:master"));
command.setForce(true);
command.call();
} catch (GitAPIException e) {
e.printStackTrace();
}
System.out.println("Deployment to web app " + app2Name + " completed");
return profile;
});
}
return Flux.just(indexable);
});
Flux.merge(app1Observable, app234Observable).blockLast();
System.out.println("Warming up " + app1Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app2Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app3Url + "...");
Utils.curl("http:
System.out.println("Warming up " + app4Url + "...");
Utils.curl("http:
SdkContext.sleep(5000);
System.out.println("CURLing " + app1Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app2Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app3Url + "...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app4Url + "...");
System.out.println(Utils.curl("http:
return true;
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
} | if (indexable instanceof WebApp) { | public static boolean runSample(final Azure azure) {
final String suffix = ".azurewebsites.net";
final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20);
final String app2Name = azure.sdkContext().randomResourceName("webapp2-", 20);
final String app3Name = azure.sdkContext().randomResourceName("webapp3-", 20);
final String app4Name = azure.sdkContext().randomResourceName("webapp4-", 20);
final String app1Url = app1Name + suffix;
final String app2Url = app2Name + suffix;
final String app3Url = app3Name + suffix;
final String app4Url = app4Name + suffix;
final String planName = azure.sdkContext().randomResourceName("jplan_", 15);
final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24);
try {
System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
Flux<?> app1Observable = azure.webApps().define(app1Name)
.withRegion(Region.US_WEST)
.withNewResourceGroup(rgName)
.withNewWindowsPlan(PricingTier.STANDARD_S1)
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync()
.flatMapMany(app -> {
System.out.println("Created web app " + app.name());
return Flux.merge(
Flux.just(app),
app.getPublishingProfileAsync()
.map(publishingProfile -> {
System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
Utils.uploadFileViaFtp(publishingProfile,
"helloworld.war",
ManageWebAppSourceControlAsync.class.getResourceAsStream("/helloworld.war"));
System.out.println("Deployment helloworld.war to web app " + app1Name + " completed");
return publishingProfile;
}));
});
System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
System.out.println("Creating another web app " + app3Name + "...");
System.out.println("Creating another web app " + app4Name + "...");
Flux<?> app234Observable = azure.appServicePlans()
.getByResourceGroupAsync(rgName, planName)
.flatMapMany(plan -> {
return Flux.merge(
azure.webApps().define(app2Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.withLocalGitSourceControl()
.withJavaVersion(JavaVersion.JAVA_8_NEWEST)
.withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
.createAsync(),
azure.webApps().define(app3Name)
.withExistingWindowsPlan(plan)
.withNewResourceGroup(rgName)
.defineSourceControl()
.withPublicGitRepository(
"https:
.withBranch("master")
.attach()
.createAsync(),
azure.webApps()
.define(app4Name)
.withExistingWindowsPlan(plan)
.withExistingResourceGroup(rgName)
.createAsync());
}).flatMap(app -> {
System.out.println("Created web app " + app.name());
if (!app.name().equals(app2Name)) {
return Flux.just(app);
}
return app.getPublishingProfileAsync()
.map(profile -> {
System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
Git git = null;
try {
git = Git
.init()
.setDirectory(new File(
ManageWebAppSourceControlAsync.class.getResource(
"/azure-samples-appservice-helloworld/")
.getPath()))
.call();
git.add().addFilepattern(".").call();
git.commit().setMessage("Initial commit").call();
PushCommand command = git.push();
command.setRemote(profile.gitUrl());
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
command.setRefSpecs(new RefSpec("master:master"));
command.setForce(true);
command.call();
} catch (GitAPIException e) {
e.printStackTrace();
}
System.out.println("Deployment to web app " + app2Name + " completed");
return profile;
});
});
Flux.merge(app1Observable, app234Observable).blockLast();
System.out.println("Warming up " + app1Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app2Url + "/helloworld...");
Utils.curl("http:
System.out.println("Warming up " + app3Url + "...");
Utils.curl("http:
System.out.println("Warming up " + app4Url + "...");
Utils.curl("http:
SdkContext.sleep(5000);
System.out.println("CURLing " + app1Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app2Url + "/helloworld...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app3Url + "...");
System.out.println(Utils.curl("http:
System.out.println("CURLing " + app4Url + "...");
System.out.println(Utils.curl("http:
return true;
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
} | class ManageWebAppSourceControlAsync {
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential = new DefaultAzureCredentialBuilder()
.build();
Azure azure = Azure
.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
System.out.println("Selected subscription: " + azure.subscriptionId());
runSample(azure);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} | class ManageWebAppSourceControlAsync {
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential = new DefaultAzureCredentialBuilder()
.build();
Azure azure = Azure
.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
System.out.println("Selected subscription: " + azure.subscriptionId());
runSample(azure);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} |
I suspect this failure/assertion doesn't have any effect as this is happening on a different thread which is not joined. | public void addressResolutionStatistics() {
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());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> writeResourceResponse = container.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("\"errorMessage\":null");
assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("\"errorMessage\":\"io.netty" +
".channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information");
client.close();
client = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
container =
client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
AsyncDocumentClient asyncDocumentClient = client.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 =
container.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("\"errorMessage\":null");
assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"errorMessage\":\"io.netty" +
".channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information");
} catch (Exception ex) {
fail("This test should not throw exception");
} finally {
if (client != null) {
client.close();
}
}
} | fail(e.getMessage()); | 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("\"errorMessage\":null");
assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("\"errorMessage\":\"io.netty" +
".channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information");
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("\"errorMessage\":null");
assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"errorMessage\":\"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();
}
}
} | class CosmosDiagnosticsTest extends TestSuiteBase {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final DateTimeFormatter RESPONSE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss" + ".SSS").withLocale(Locale.US).withZone(ZoneOffset.UTC);
private CosmosClient gatewayClient;
private CosmosClient directClient;
private CosmosContainer container;
private CosmosAsyncContainer cosmosAsyncContainer;
@BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT)
public void beforeClass() throws Exception {
assertThat(this.gatewayClient).isNull();
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.buildClient();
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient());
container = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
}
@AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true)
public void afterClass() {
assertThat(this.gatewayClient).isNotNull();
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 },
};
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void gatewayDiagnostics() {
CosmosClient testGatewayClient = null;
try {
testGatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.buildClient();
CosmosContainer container =
testGatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode);
String diagnostics = createResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\"");
assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null"));
assertThat(diagnostics).contains("\"operationType\":\"Create\"");
assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\"");
assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\"");
assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineGateway(diagnostics);
validateJson(diagnostics);
} finally {
if (testGatewayClient != null) {
testGatewayClient.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void gatewayDiagnosticsOnException() {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = null;
try {
createResponse = this.container.createItem(internalObjectNode);
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey"));
CosmosItemResponse<InternalObjectNode> readResponse =
this.container.readItem(BridgeInternal.getProperties(createResponse).getId(),
new PartitionKey("wrongPartitionKey"),
InternalObjectNode.class);
fail("request should fail as partition key is wrong");
} catch (CosmosException exception) {
String diagnostics = exception.getDiagnostics().toString();
assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND);
assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\"");
assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null"));
assertThat(diagnostics).contains("\"statusCode\":404");
assertThat(diagnostics).contains("\"operationType\":\"Read\"");
assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\"");
assertThat(exception.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineGateway(diagnostics);
validateJson(diagnostics);
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void systemDiagnosticsForSystemStateInformation() {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = this.container.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\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void directDiagnostics() {
CosmosClient testDirectClient = null;
try {
testDirectClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
CosmosContainer cosmosContainer =
testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode);
String diagnostics = createResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\"");
assertThat(diagnostics).contains("supplementalResponseStatisticsList");
assertThat(diagnostics).contains("\"gatewayStatistics\":null");
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\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineDirect(diagnostics);
validateJson(diagnostics);
} finally {
if (testDirectClient != null) {
testDirectClient.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void queryPlanDiagnostics() {
CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
List<String> itemIdList = new ArrayList<>();
for(int i = 0; i< 100; i++) {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.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 = cosmosContainer.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("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)=");
} else {
assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)=");
}
feedResponseCounter++;
}
}
}
@Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT)
public void queryMetrics(String query, Boolean qmEnabled) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (qmEnabled != null) {
options.setQueryMetricsEnabled(qmEnabled);
}
boolean qroupByFirstResponse = true;
Iterator<FeedResponse<InternalObjectNode>> iterator = this.container.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);
if (query.contains("group by")) {
qroupByFirstResponse = false;
}
}
}
}
private static void validateQueryDiagnostics(
String queryDiagnostics,
Boolean qmEnabled,
boolean expectQueryPlanDiagnostics) {
if (qmEnabled == null || qmEnabled == true) {
assertThat(queryDiagnostics).contains("Retrieved Document Count");
assertThat(queryDiagnostics).contains("Query Preparation Times");
assertThat(queryDiagnostics).contains("Runtime Execution Times");
assertThat(queryDiagnostics).contains("Partition Execution Timeline");
} else {
assertThat(queryDiagnostics).doesNotContain("Retrieved Document Count");
assertThat(queryDiagnostics).doesNotContain("Query Preparation Times");
assertThat(queryDiagnostics).doesNotContain("Runtime Execution Times");
assertThat(queryDiagnostics).doesNotContain("Partition Execution Timeline");
}
if (expectQueryPlanDiagnostics) {
assertThat(queryDiagnostics).contains("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)=");
} else {
assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)=");
}
}
@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 = container.createItem(internalObjectNode);
}
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (qmEnabled != null) {
options = options.setQueryMetricsEnabled(qmEnabled);
}
ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5);
Iterator<FeedResponse<InternalObjectNode>> iterator =
this.container
.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() {
CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = null;
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());
createResponse = container.createItem(internalObjectNode);
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey"));
CosmosItemResponse<InternalObjectNode> readResponse =
cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(),
new PartitionKey("wrongPartitionKey"),
InternalObjectNode.class);
fail("request should fail as partition key is wrong");
} catch (CosmosException exception) {
String diagnostics = exception.getDiagnostics().toString();
assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND);
assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\"");
assertThat(exception.getDiagnostics().getDuration()).isNotNull();
validateJson(diagnostics);
} finally {
if (client != null) {
client.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void supplementalResponseStatisticsList() throws Exception {
ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics();
for (int i = 0; i < 15; i++) {
RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(OperationType.Head, ResourceType.Document);
clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, 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(OperationType.Head, ResourceType.Document);
clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, 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();
String formattedInstant = RESPONSE_TIME_FORMATTER.format(Instant.now());
String[] requestResponseTimeUTCList = requestResponseTimeUTC.split(" ");
String[] formattedInstantList = formattedInstant.split(" ");
assertThat(requestResponseTimeUTC.length()).isEqualTo(formattedInstant.length());
assertThat(requestResponseTimeUTCList.length).isEqualTo(formattedInstantList.length);
assertThat(requestResponseTimeUTCList[0]).isEqualTo(formattedInstantList[0]);
assertThat(requestResponseTimeUTCList[1]).isEqualTo(formattedInstantList[1]);
assertThat(requestResponseTimeUTCList[2]).isEqualTo(formattedInstantList[2]);
assertThat(node.get("requestResponseTimeUTC")).isNotNull();
assertThat(node.get("requestOperationType")).isNotNull();
assertThat(node.get("requestOperationType")).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.container.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.container.createItem(testItem);
diagnostics = itemResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\"");
testItem.id = "TestId2";
testItem.mypk = "TestPk";
itemResponse = this.container.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.container.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\":\"" + Utils.getUserAgent() + "\"");
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
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\":\"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\":\"pipelined\"");
assertThat(diagnostics).contains("\"eventName\":\"transitTime\"");
assertThat(diagnostics).contains("\"eventName\":\"received\"");
assertThat(diagnostics).contains("\"eventName\":\"completed\"");
}
private void validateJson(String jsonInString) {
try {
OBJECT_MAPPER.readTree(jsonInString);
} catch(JsonProcessingException ex) {
fail("Diagnostic string is not in json format");
}
}
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);
}
public static class TestItem {
public String id;
public String mypk;
public TestItem() {
}
}
} | class CosmosDiagnosticsTest extends TestSuiteBase {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final DateTimeFormatter RESPONSE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss" + ".SSS").withLocale(Locale.US).withZone(ZoneOffset.UTC);
private CosmosClient gatewayClient;
private CosmosClient directClient;
private CosmosContainer container;
private CosmosAsyncContainer cosmosAsyncContainer;
@BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT)
public void beforeClass() throws Exception {
assertThat(this.gatewayClient).isNull();
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.buildClient();
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient());
container = gatewayClient.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 },
};
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void gatewayDiagnostics() {
CosmosClient testGatewayClient = null;
try {
testGatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.buildClient();
CosmosContainer container =
testGatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode);
String diagnostics = createResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\"");
assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null"));
assertThat(diagnostics).contains("\"operationType\":\"Create\"");
assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\"");
assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\"");
assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineGateway(diagnostics);
validateJson(diagnostics);
} finally {
if (testGatewayClient != null) {
testGatewayClient.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void gatewayDiagnosticsOnException() {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = null;
try {
createResponse = this.container.createItem(internalObjectNode);
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey"));
CosmosItemResponse<InternalObjectNode> readResponse =
this.container.readItem(BridgeInternal.getProperties(createResponse).getId(),
new PartitionKey("wrongPartitionKey"),
InternalObjectNode.class);
fail("request should fail as partition key is wrong");
} catch (CosmosException exception) {
String diagnostics = exception.getDiagnostics().toString();
assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND);
assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\"");
assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null"));
assertThat(diagnostics).contains("\"statusCode\":404");
assertThat(diagnostics).contains("\"operationType\":\"Read\"");
assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\"");
assertThat(exception.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineGateway(diagnostics);
validateJson(diagnostics);
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void systemDiagnosticsForSystemStateInformation() {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = this.container.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\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void directDiagnostics() {
CosmosClient testDirectClient = null;
try {
testDirectClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
CosmosContainer cosmosContainer =
testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode);
String diagnostics = createResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\"");
assertThat(diagnostics).contains("supplementalResponseStatisticsList");
assertThat(diagnostics).contains("\"gatewayStatistics\":null");
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\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineDirect(diagnostics);
validateJson(diagnostics);
} finally {
if (testDirectClient != null) {
testDirectClient.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void queryPlanDiagnostics() {
CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
List<String> itemIdList = new ArrayList<>();
for(int i = 0; i< 100; i++) {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.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 = cosmosContainer.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("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)=");
} else {
assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)=");
}
feedResponseCounter++;
}
}
}
@Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT)
public void queryMetrics(String query, Boolean qmEnabled) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (qmEnabled != null) {
options.setQueryMetricsEnabled(qmEnabled);
}
boolean qroupByFirstResponse = true;
Iterator<FeedResponse<InternalObjectNode>> iterator = this.container.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);
if (query.contains("group by")) {
qroupByFirstResponse = false;
}
}
}
}
private static void validateQueryDiagnostics(
String queryDiagnostics,
Boolean qmEnabled,
boolean expectQueryPlanDiagnostics) {
if (qmEnabled == null || qmEnabled == true) {
assertThat(queryDiagnostics).contains("Retrieved Document Count");
assertThat(queryDiagnostics).contains("Query Preparation Times");
assertThat(queryDiagnostics).contains("Runtime Execution Times");
assertThat(queryDiagnostics).contains("Partition Execution Timeline");
} else {
assertThat(queryDiagnostics).doesNotContain("Retrieved Document Count");
assertThat(queryDiagnostics).doesNotContain("Query Preparation Times");
assertThat(queryDiagnostics).doesNotContain("Runtime Execution Times");
assertThat(queryDiagnostics).doesNotContain("Partition Execution Timeline");
}
if (expectQueryPlanDiagnostics) {
assertThat(queryDiagnostics).contains("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)=");
} else {
assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)=");
}
}
@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 = container.createItem(internalObjectNode);
}
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (qmEnabled != null) {
options = options.setQueryMetricsEnabled(qmEnabled);
}
ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5);
Iterator<FeedResponse<InternalObjectNode>> iterator =
this.container
.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() {
CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = null;
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());
createResponse = container.createItem(internalObjectNode);
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey"));
CosmosItemResponse<InternalObjectNode> readResponse =
cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(),
new PartitionKey("wrongPartitionKey"),
InternalObjectNode.class);
fail("request should fail as partition key is wrong");
} catch (CosmosException exception) {
String diagnostics = exception.getDiagnostics().toString();
assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND);
assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\"");
assertThat(exception.getDiagnostics().getDuration()).isNotNull();
validateJson(diagnostics);
} finally {
if (client != null) {
client.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void supplementalResponseStatisticsList() throws Exception {
ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics();
for (int i = 0; i < 15; i++) {
RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(OperationType.Head, ResourceType.Document);
clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, 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(OperationType.Head, ResourceType.Document);
clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, 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();
String formattedInstant = RESPONSE_TIME_FORMATTER.format(Instant.now());
String[] requestResponseTimeUTCList = requestResponseTimeUTC.split(" ");
String[] formattedInstantList = formattedInstant.split(" ");
assertThat(requestResponseTimeUTC.length()).isEqualTo(formattedInstant.length());
assertThat(requestResponseTimeUTCList.length).isEqualTo(formattedInstantList.length);
assertThat(requestResponseTimeUTCList[0]).isEqualTo(formattedInstantList[0]);
assertThat(requestResponseTimeUTCList[1]).isEqualTo(formattedInstantList[1]);
assertThat(requestResponseTimeUTCList[2]).isEqualTo(formattedInstantList[2]);
assertThat(node.get("requestResponseTimeUTC")).isNotNull();
assertThat(node.get("requestOperationType")).isNotNull();
assertThat(node.get("requestOperationType")).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.container.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.container.createItem(testItem);
diagnostics = itemResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\"");
testItem.id = "TestId2";
testItem.mypk = "TestPk";
itemResponse = this.container.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.container.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\":\"" + Utils.getUserAgent() + "\"");
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
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\":\"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\":\"pipelined\"");
assertThat(diagnostics).contains("\"eventName\":\"transitTime\"");
assertThat(diagnostics).contains("\"eventName\":\"received\"");
assertThat(diagnostics).contains("\"eventName\":\"completed\"");
}
private void validateJson(String jsonInString) {
try {
OBJECT_MAPPER.readTree(jsonInString);
} catch(JsonProcessingException ex) {
fail("Diagnostic string is not in json format");
}
}
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);
}
public static class TestItem {
public String id;
public String mypk;
public TestItem() {
}
}
} |
you don't need to catch exception. and fail. the test will fail regardless of this. if the exception is thrown. | public void addressResolutionStatistics() {
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());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> writeResourceResponse = container.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("\"errorMessage\":null");
assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("\"errorMessage\":\"io.netty" +
".channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information");
client.close();
client = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
container =
client.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
AsyncDocumentClient asyncDocumentClient = client.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 =
container.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("\"errorMessage\":null");
assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"errorMessage\":\"io.netty" +
".channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information");
} catch (Exception ex) {
fail("This test should not throw exception");
} finally {
if (client != null) {
client.close();
}
}
} | fail("This test should not throw exception"); | 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("\"errorMessage\":null");
assertThat(writeResourceResponse.getDiagnostics().toString()).doesNotContain("\"errorMessage\":\"io.netty" +
".channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information");
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("\"errorMessage\":null");
assertThat(readResourceResponse.getDiagnostics().toString()).contains("\"errorMessage\":\"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();
}
}
} | class CosmosDiagnosticsTest extends TestSuiteBase {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final DateTimeFormatter RESPONSE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss" + ".SSS").withLocale(Locale.US).withZone(ZoneOffset.UTC);
private CosmosClient gatewayClient;
private CosmosClient directClient;
private CosmosContainer container;
private CosmosAsyncContainer cosmosAsyncContainer;
@BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT)
public void beforeClass() throws Exception {
assertThat(this.gatewayClient).isNull();
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.buildClient();
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient());
container = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
}
@AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true)
public void afterClass() {
assertThat(this.gatewayClient).isNotNull();
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 },
};
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void gatewayDiagnostics() {
CosmosClient testGatewayClient = null;
try {
testGatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.buildClient();
CosmosContainer container =
testGatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode);
String diagnostics = createResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\"");
assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null"));
assertThat(diagnostics).contains("\"operationType\":\"Create\"");
assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\"");
assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\"");
assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineGateway(diagnostics);
validateJson(diagnostics);
} finally {
if (testGatewayClient != null) {
testGatewayClient.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void gatewayDiagnosticsOnException() {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = null;
try {
createResponse = this.container.createItem(internalObjectNode);
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey"));
CosmosItemResponse<InternalObjectNode> readResponse =
this.container.readItem(BridgeInternal.getProperties(createResponse).getId(),
new PartitionKey("wrongPartitionKey"),
InternalObjectNode.class);
fail("request should fail as partition key is wrong");
} catch (CosmosException exception) {
String diagnostics = exception.getDiagnostics().toString();
assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND);
assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\"");
assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null"));
assertThat(diagnostics).contains("\"statusCode\":404");
assertThat(diagnostics).contains("\"operationType\":\"Read\"");
assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\"");
assertThat(exception.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineGateway(diagnostics);
validateJson(diagnostics);
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void systemDiagnosticsForSystemStateInformation() {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = this.container.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\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void directDiagnostics() {
CosmosClient testDirectClient = null;
try {
testDirectClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
CosmosContainer cosmosContainer =
testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode);
String diagnostics = createResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\"");
assertThat(diagnostics).contains("supplementalResponseStatisticsList");
assertThat(diagnostics).contains("\"gatewayStatistics\":null");
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\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineDirect(diagnostics);
validateJson(diagnostics);
} finally {
if (testDirectClient != null) {
testDirectClient.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void queryPlanDiagnostics() {
CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
List<String> itemIdList = new ArrayList<>();
for(int i = 0; i< 100; i++) {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.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 = cosmosContainer.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("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)=");
} else {
assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)=");
}
feedResponseCounter++;
}
}
}
@Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT)
public void queryMetrics(String query, Boolean qmEnabled) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (qmEnabled != null) {
options.setQueryMetricsEnabled(qmEnabled);
}
boolean qroupByFirstResponse = true;
Iterator<FeedResponse<InternalObjectNode>> iterator = this.container.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);
if (query.contains("group by")) {
qroupByFirstResponse = false;
}
}
}
}
private static void validateQueryDiagnostics(
String queryDiagnostics,
Boolean qmEnabled,
boolean expectQueryPlanDiagnostics) {
if (qmEnabled == null || qmEnabled == true) {
assertThat(queryDiagnostics).contains("Retrieved Document Count");
assertThat(queryDiagnostics).contains("Query Preparation Times");
assertThat(queryDiagnostics).contains("Runtime Execution Times");
assertThat(queryDiagnostics).contains("Partition Execution Timeline");
} else {
assertThat(queryDiagnostics).doesNotContain("Retrieved Document Count");
assertThat(queryDiagnostics).doesNotContain("Query Preparation Times");
assertThat(queryDiagnostics).doesNotContain("Runtime Execution Times");
assertThat(queryDiagnostics).doesNotContain("Partition Execution Timeline");
}
if (expectQueryPlanDiagnostics) {
assertThat(queryDiagnostics).contains("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)=");
} else {
assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)=");
}
}
@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 = container.createItem(internalObjectNode);
}
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (qmEnabled != null) {
options = options.setQueryMetricsEnabled(qmEnabled);
}
ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5);
Iterator<FeedResponse<InternalObjectNode>> iterator =
this.container
.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() {
CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = null;
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());
createResponse = container.createItem(internalObjectNode);
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey"));
CosmosItemResponse<InternalObjectNode> readResponse =
cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(),
new PartitionKey("wrongPartitionKey"),
InternalObjectNode.class);
fail("request should fail as partition key is wrong");
} catch (CosmosException exception) {
String diagnostics = exception.getDiagnostics().toString();
assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND);
assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\"");
assertThat(exception.getDiagnostics().getDuration()).isNotNull();
validateJson(diagnostics);
} finally {
if (client != null) {
client.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void supplementalResponseStatisticsList() throws Exception {
ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics();
for (int i = 0; i < 15; i++) {
RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(OperationType.Head, ResourceType.Document);
clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, 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(OperationType.Head, ResourceType.Document);
clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, 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();
String formattedInstant = RESPONSE_TIME_FORMATTER.format(Instant.now());
String[] requestResponseTimeUTCList = requestResponseTimeUTC.split(" ");
String[] formattedInstantList = formattedInstant.split(" ");
assertThat(requestResponseTimeUTC.length()).isEqualTo(formattedInstant.length());
assertThat(requestResponseTimeUTCList.length).isEqualTo(formattedInstantList.length);
assertThat(requestResponseTimeUTCList[0]).isEqualTo(formattedInstantList[0]);
assertThat(requestResponseTimeUTCList[1]).isEqualTo(formattedInstantList[1]);
assertThat(requestResponseTimeUTCList[2]).isEqualTo(formattedInstantList[2]);
assertThat(node.get("requestResponseTimeUTC")).isNotNull();
assertThat(node.get("requestOperationType")).isNotNull();
assertThat(node.get("requestOperationType")).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.container.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.container.createItem(testItem);
diagnostics = itemResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\"");
testItem.id = "TestId2";
testItem.mypk = "TestPk";
itemResponse = this.container.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.container.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\":\"" + Utils.getUserAgent() + "\"");
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
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\":\"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\":\"pipelined\"");
assertThat(diagnostics).contains("\"eventName\":\"transitTime\"");
assertThat(diagnostics).contains("\"eventName\":\"received\"");
assertThat(diagnostics).contains("\"eventName\":\"completed\"");
}
private void validateJson(String jsonInString) {
try {
OBJECT_MAPPER.readTree(jsonInString);
} catch(JsonProcessingException ex) {
fail("Diagnostic string is not in json format");
}
}
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);
}
public static class TestItem {
public String id;
public String mypk;
public TestItem() {
}
}
} | class CosmosDiagnosticsTest extends TestSuiteBase {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final DateTimeFormatter RESPONSE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss" + ".SSS").withLocale(Locale.US).withZone(ZoneOffset.UTC);
private CosmosClient gatewayClient;
private CosmosClient directClient;
private CosmosContainer container;
private CosmosAsyncContainer cosmosAsyncContainer;
@BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT)
public void beforeClass() throws Exception {
assertThat(this.gatewayClient).isNull();
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.buildClient();
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(this.gatewayClient.asyncClient());
container = gatewayClient.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 },
};
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void gatewayDiagnostics() {
CosmosClient testGatewayClient = null;
try {
testGatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.buildClient();
CosmosContainer container =
testGatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode);
String diagnostics = createResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\"");
assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null"));
assertThat(diagnostics).contains("\"operationType\":\"Create\"");
assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\"");
assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\"");
assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineGateway(diagnostics);
validateJson(diagnostics);
} finally {
if (testGatewayClient != null) {
testGatewayClient.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void gatewayDiagnosticsOnException() {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = null;
try {
createResponse = this.container.createItem(internalObjectNode);
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey"));
CosmosItemResponse<InternalObjectNode> readResponse =
this.container.readItem(BridgeInternal.getProperties(createResponse).getId(),
new PartitionKey("wrongPartitionKey"),
InternalObjectNode.class);
fail("request should fail as partition key is wrong");
} catch (CosmosException exception) {
String diagnostics = exception.getDiagnostics().toString();
assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND);
assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\"");
assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null"));
assertThat(diagnostics).contains("\"statusCode\":404");
assertThat(diagnostics).contains("\"operationType\":\"Read\"");
assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\"");
assertThat(exception.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineGateway(diagnostics);
validateJson(diagnostics);
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void systemDiagnosticsForSystemStateInformation() {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = this.container.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\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void directDiagnostics() {
CosmosClient testDirectClient = null;
try {
testDirectClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.buildClient();
CosmosContainer cosmosContainer =
testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode);
String diagnostics = createResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\"");
assertThat(diagnostics).contains("supplementalResponseStatisticsList");
assertThat(diagnostics).contains("\"gatewayStatistics\":null");
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\":\"" + Utils.getUserAgent() + "\"");
assertThat(createResponse.getDiagnostics().getDuration()).isNotNull();
validateTransportRequestTimelineDirect(diagnostics);
validateJson(diagnostics);
} finally {
if (testDirectClient != null) {
testDirectClient.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void queryPlanDiagnostics() {
CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
List<String> itemIdList = new ArrayList<>();
for(int i = 0; i< 100; i++) {
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.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 = cosmosContainer.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("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)=");
} else {
assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)=");
}
feedResponseCounter++;
}
}
}
@Test(groups = {"simple"}, dataProvider = "query", timeOut = TIMEOUT)
public void queryMetrics(String query, Boolean qmEnabled) {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (qmEnabled != null) {
options.setQueryMetricsEnabled(qmEnabled);
}
boolean qroupByFirstResponse = true;
Iterator<FeedResponse<InternalObjectNode>> iterator = this.container.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);
if (query.contains("group by")) {
qroupByFirstResponse = false;
}
}
}
}
private static void validateQueryDiagnostics(
String queryDiagnostics,
Boolean qmEnabled,
boolean expectQueryPlanDiagnostics) {
if (qmEnabled == null || qmEnabled == true) {
assertThat(queryDiagnostics).contains("Retrieved Document Count");
assertThat(queryDiagnostics).contains("Query Preparation Times");
assertThat(queryDiagnostics).contains("Runtime Execution Times");
assertThat(queryDiagnostics).contains("Partition Execution Timeline");
} else {
assertThat(queryDiagnostics).doesNotContain("Retrieved Document Count");
assertThat(queryDiagnostics).doesNotContain("Query Preparation Times");
assertThat(queryDiagnostics).doesNotContain("Runtime Execution Times");
assertThat(queryDiagnostics).doesNotContain("Partition Execution Timeline");
}
if (expectQueryPlanDiagnostics) {
assertThat(queryDiagnostics).contains("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).contains("QueryPlan Duration (ms)=");
} else {
assertThat(queryDiagnostics).doesNotContain("QueryPlan Start Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan End Time (UTC)=");
assertThat(queryDiagnostics).doesNotContain("QueryPlan Duration (ms)=");
}
}
@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 = container.createItem(internalObjectNode);
}
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
if (qmEnabled != null) {
options = options.setQueryMetricsEnabled(qmEnabled);
}
ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(options, 5);
Iterator<FeedResponse<InternalObjectNode>> iterator =
this.container
.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() {
CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId());
InternalObjectNode internalObjectNode = getInternalObjectNode();
CosmosItemResponse<InternalObjectNode> createResponse = null;
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());
createResponse = container.createItem(internalObjectNode);
CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions();
ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey("wrongPartitionKey"));
CosmosItemResponse<InternalObjectNode> readResponse =
cosmosContainer.readItem(BridgeInternal.getProperties(createResponse).getId(),
new PartitionKey("wrongPartitionKey"),
InternalObjectNode.class);
fail("request should fail as partition key is wrong");
} catch (CosmosException exception) {
String diagnostics = exception.getDiagnostics().toString();
assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND);
assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\"");
assertThat(exception.getDiagnostics().getDuration()).isNotNull();
validateJson(diagnostics);
} finally {
if (client != null) {
client.close();
}
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void supplementalResponseStatisticsList() throws Exception {
ClientSideRequestStatistics clientSideRequestStatistics = new ClientSideRequestStatistics();
for (int i = 0; i < 15; i++) {
RxDocumentServiceRequest rxDocumentServiceRequest = RxDocumentServiceRequest.create(OperationType.Head, ResourceType.Document);
clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, 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(OperationType.Head, ResourceType.Document);
clientSideRequestStatistics.recordResponse(rxDocumentServiceRequest, 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();
String formattedInstant = RESPONSE_TIME_FORMATTER.format(Instant.now());
String[] requestResponseTimeUTCList = requestResponseTimeUTC.split(" ");
String[] formattedInstantList = formattedInstant.split(" ");
assertThat(requestResponseTimeUTC.length()).isEqualTo(formattedInstant.length());
assertThat(requestResponseTimeUTCList.length).isEqualTo(formattedInstantList.length);
assertThat(requestResponseTimeUTCList[0]).isEqualTo(formattedInstantList[0]);
assertThat(requestResponseTimeUTCList[1]).isEqualTo(formattedInstantList[1]);
assertThat(requestResponseTimeUTCList[2]).isEqualTo(formattedInstantList[2]);
assertThat(node.get("requestResponseTimeUTC")).isNotNull();
assertThat(node.get("requestOperationType")).isNotNull();
assertThat(node.get("requestOperationType")).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.container.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.container.createItem(testItem);
diagnostics = itemResponse.getDiagnostics().toString();
assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\"");
testItem.id = "TestId2";
testItem.mypk = "TestPk";
itemResponse = this.container.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.container.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\":\"" + Utils.getUserAgent() + "\"");
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
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\":\"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\":\"pipelined\"");
assertThat(diagnostics).contains("\"eventName\":\"transitTime\"");
assertThat(diagnostics).contains("\"eventName\":\"received\"");
assertThat(diagnostics).contains("\"eventName\":\"completed\"");
}
private void validateJson(String jsonInString) {
try {
OBJECT_MAPPER.readTree(jsonInString);
} catch(JsonProcessingException ex) {
fail("Diagnostic string is not in json format");
}
}
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);
}
public static class TestItem {
public String id;
public String mypk;
public TestItem() {
}
}
} |
For the entityPath and hostName values, do we want to update the `ServiceBusSenderAsyncClient` or we should be able to retrieve it some other way? | private Mono<Void> sendInternal(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(batch)) {
return monoError(logger, new NullPointerException("'batch' cannot be null."));
}
final boolean isTracingEnabled = tracerProvider.isEnabled();
final AtomicReference<Context> parentContext = isTracingEnabled
? new AtomicReference<>(Context.NONE)
: null;
if (batch.getMessages().isEmpty()) {
logger.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
logger.info("Sending batch with size[{}].", batch.getCount());
Context sharedContext = null;
final List<org.apache.qpid.proton.message.Message> messages = new ArrayList<>();
for (int i = 0; i < batch.getMessages().size(); i++) {
final ServiceBusMessage event = batch.getMessages().get(i);
if (isTracingEnabled) {
parentContext.set(event.getContext());
if (i == 0) {
sharedContext = tracerProvider.getSharedSpanBuilder(parentContext.get());
}
tracerProvider.addSpanLinks(sharedContext.addData(SPAN_CONTEXT_KEY, event.getContext()));
}
final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(event);
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
message.setMessageAnnotations(messageAnnotations);
messages.add(message);
}
if (isTracingEnabled) {
final Context finalSharedContext = sharedContext == null
? Context.NONE
: sharedContext
.addData(ENTITY_PATH_KEY, "entityPath")
.addData(HOST_NAME_KEY, "hostName")
.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE);
parentContext.set(tracerProvider.startSpan(finalSharedContext, ProcessKind.SEND));
}
return withRetry(
getSendLink().flatMap(link -> {
if (transactionContext != null && transactionContext.getTransactionId() != null) {
final TransactionalState deliveryState = new TransactionalState();
deliveryState.setTxnId(new Binary(transactionContext.getTransactionId().array()));
return messages.size() == 1
? link.send(messages.get(0), deliveryState)
: link.send(messages, deliveryState);
} else {
return messages.size() == 1
? link.send(messages.get(0))
: link.send(messages);
}
})
.doOnEach(signal -> {
if (isTracingEnabled) {
tracerProvider.endSpan(parentContext.get(), signal);
}
})
.doOnError(error -> {
if (isTracingEnabled) {
tracerProvider.endSpan(parentContext.get(), Signal.error(error));
}
}), retryOptions.getTryTimeout(), retryPolicy);
} | .addData(HOST_NAME_KEY, "hostName") | private Mono<Void> sendInternal(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(batch)) {
return monoError(logger, new NullPointerException("'batch' cannot be null."));
}
final boolean isTracingEnabled = tracerProvider.isEnabled();
final AtomicReference<Context> parentContext = isTracingEnabled
? new AtomicReference<>(Context.NONE)
: null;
if (batch.getMessages().isEmpty()) {
logger.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
logger.info("Sending batch with size[{}].", batch.getCount());
Context sharedContext = null;
final List<org.apache.qpid.proton.message.Message> messages = new ArrayList<>();
for (int i = 0; i < batch.getMessages().size(); i++) {
final ServiceBusMessage event = batch.getMessages().get(i);
if (isTracingEnabled) {
parentContext.set(event.getContext());
if (i == 0) {
sharedContext = tracerProvider.getSharedSpanBuilder(SERVICE_BASE_NAME, parentContext.get());
}
tracerProvider.addSpanLinks(sharedContext.addData(SPAN_CONTEXT_KEY, event.getContext()));
}
final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(event);
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
message.setMessageAnnotations(messageAnnotations);
messages.add(message);
}
if (isTracingEnabled) {
final Context finalSharedContext = sharedContext == null
? Context.NONE
: sharedContext
.addData(ENTITY_PATH_KEY, entityName)
.addData(HOST_NAME_KEY, connectionProcessor.getFullyQualifiedNamespace())
.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE);
parentContext.set(tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, finalSharedContext, ProcessKind.SEND));
}
return withRetry(
getSendLink().flatMap(link -> {
if (transactionContext != null && transactionContext.getTransactionId() != null) {
final TransactionalState deliveryState = new TransactionalState();
deliveryState.setTxnId(new Binary(transactionContext.getTransactionId().array()));
return messages.size() == 1
? link.send(messages.get(0), deliveryState)
: link.send(messages, deliveryState);
} else {
return messages.size() == 1
? link.send(messages.get(0))
: link.send(messages);
}
}), retryOptions.getTryTimeout(), retryPolicy)
.doOnEach(signal -> {
if (isTracingEnabled) {
tracerProvider.endSpan(parentContext.get(), signal);
}
});
} | class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final String AZ_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions();
private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class);
private final AtomicReference<String> linkName = new AtomicReference<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final AmqpRetryOptions retryOptions;
private final AmqpRetryPolicy retryPolicy;
private final MessagingEntityType entityType;
private final Runnable onClientClose;
private final String entityName;
private final ServiceBusConnectionProcessor connectionProcessor;
private final String viaEntityName;
/**
* Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to a Service Bus entity.
*/
ServiceBusSenderAsyncClient(String entityName, MessagingEntityType entityType,
ServiceBusConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider,
MessageSerializer messageSerializer, Runnable onClientClose, String viaEntityName) {
this.messageSerializer = Objects.requireNonNull(messageSerializer,
"'messageSerializer' cannot be null.");
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null.");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor,
"'connectionProcessor' cannot be null.");
this.tracerProvider = tracerProvider;
this.retryPolicy = getRetryPolicy(retryOptions);
this.entityType = entityType;
this.viaEntityName = viaEntityName;
this.onClientClose = onClientClose;
}
/**
* Gets the fully qualified namespace.
*
* @return The fully qualified namespace.
*/
public String getFullyQualifiedNamespace() {
return connectionProcessor.getFullyQualifiedNamespace();
}
/**
* Gets the name of the Service Bus resource.
*
* @return The name of the Service Bus resource.
*/
public String getEntityPath() {
return entityName;
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
*/
public Mono<Void> sendMessage(ServiceBusMessage message) {
if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
}
return sendInternal(Flux.just(message), null);
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
*/
public Mono<Void> sendMessage(ServiceBusMessage message, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(Flux.just(message), transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages
* exceed the maximum size of a single batch, an exception will be triggered and the send will fail.
* By default, the message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
* @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendIterable(messages, transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages exceed
* the maximum size of a single batch, an exception will be triggered and the send will fail. By default, the
* message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code messages} is {@code null}.
* @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages) {
return sendIterable(messages, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch} is {@code null}.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch) {
return sendInternal(batch, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(batch, transactionContext);
}
/**
* Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*
* @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*/
public Mono<ServiceBusMessageBatch> createBatch() {
return createBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link ServiceBusMessageBatch} configured with the options specified.
*
* @param options A set of options used to configure the {@link ServiceBusMessageBatch}.
*
* @return A new {@link ServiceBusMessageBatch} configured with the given options.
* @throws NullPointerException if {@code options} is null.
*/
public Mono<ServiceBusMessageBatch> createBatch(CreateBatchOptions options) {
if (Objects.isNull(options)) {
return monoError(logger, new NullPointerException("'options' cannot be null."));
}
final int maxSize = options.getMaximumSizeInBytes();
return getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (maxSize > maximumLinkSize) {
return monoError(logger, new IllegalArgumentException(String.format(Locale.US,
"CreateBatchOptions.getMaximumSizeInBytes (%s bytes) is larger than the link size"
+ " (%s bytes).", maxSize, maximumLinkSize)));
}
final int batchSize = maxSize > 0
? maxSize
: maximumLinkSize;
return Mono.just(
new ServiceBusMessageBatch(batchSize, link::getErrorContext, tracerProvider, messageSerializer));
}));
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message}, {@code scheduledEnqueueTime}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return scheduleMessageInternal(message, scheduledEnqueueTime, transactionContext);
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime) {
return scheduleMessageInternal(message, scheduledEnqueueTime, null);
}
/**
* Cancels the enqueuing of an already scheduled message, if it was not already enqueued.
*
* @param sequenceNumber of the scheduled message to cancel.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*
* @throws IllegalArgumentException if {@code sequenceNumber} is negative.
*/
public Mono<Void> cancelScheduledMessage(long sequenceNumber) {
if (sequenceNumber < 0) {
return monoError(logger, new IllegalArgumentException("'sequenceNumber' cannot be negative."));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.cancelScheduledMessage(sequenceNumber, linkName.get()));
}
/**
* Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along with
* {@link ServiceBusReceivedMessage} or {@code lockToken } to all operations that needs to be in
* this transaction.
*
* @return a new {@link ServiceBusTransactionContext}.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the {@link ServiceBusSenderAsyncClient}. If the client had a dedicated connection, the underlying
* connection is also closed.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
onClientClose.run();
}
private Mono<Void> sendIterable(Iterable<ServiceBusMessage> messages, ServiceBusTransactionContext transaction) {
if (Objects.isNull(messages)) {
return monoError(logger, new NullPointerException("'messages' cannot be null."));
}
return createBatch().flatMap(messageBatch -> {
messages.forEach(message -> messageBatch.tryAdd(message));
return sendInternal(messageBatch, transaction);
});
}
private Mono<Long> scheduleMessageInternal(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
}
if (Objects.isNull(scheduledEnqueueTime)) {
return monoError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null."));
}
return getSendLink()
.flatMap(link -> link.getLinkSize().flatMap(size -> {
int maxSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.schedule(message, scheduledEnqueueTime, maxSize,
link.getLinkName(), transactionContext));
}));
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*/
private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages, ServiceBusTransactionContext transactionContext) {
return getSendLink()
.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final CreateBatchOptions batchOptions = new CreateBatchOptions()
.setMaximumSizeInBytes(batchSize);
return messages.collect(new AmqpMessageCollector(batchOptions, 1,
link::getErrorContext, tracerProvider, messageSerializer));
})
.flatMap(list -> sendInternalBatch(Flux.fromIterable(list), transactionContext)));
}
private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches,
ServiceBusTransactionContext transactionContext) {
return eventBatches
.flatMap(messageBatch -> sendInternal(messageBatch, transactionContext))
.then()
.doOnError(error -> logger.error("Error sending batch.", error));
}
private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions,
entityName);
} else {
return connection.createSendLink(entityName, entityName, retryOptions, null);
}
})
.doOnNext(next -> linkName.compareAndSet(null, next.getLinkName()));
}
private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>,
List<ServiceBusMessageBatch>> {
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private final TracerProvider tracerProvider;
private final MessageSerializer serializer;
private volatile ServiceBusMessageBatch currentBatch;
AmqpMessageCollector(CreateBatchOptions options, Integer maxNumberOfBatches,
ErrorContextProvider contextProvider, TracerProvider tracerProvider, MessageSerializer serializer) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.contextProvider = contextProvider;
this.tracerProvider = tracerProvider;
this.serializer = serializer;
currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer);
}
@Override
public Supplier<List<ServiceBusMessageBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() {
return (list, event) -> {
ServiceBusMessageBatch batch = currentBatch;
if (batch.tryAdd(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer);
currentBatch.tryAdd(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<ServiceBusMessageBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() {
return list -> {
ServiceBusMessageBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
} | class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final String AZ_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions();
private static final String SERVICE_BASE_NAME = "ServiceBus.";
private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class);
private final AtomicReference<String> linkName = new AtomicReference<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final AmqpRetryOptions retryOptions;
private final AmqpRetryPolicy retryPolicy;
private final MessagingEntityType entityType;
private final Runnable onClientClose;
private final String entityName;
private final ServiceBusConnectionProcessor connectionProcessor;
private final String viaEntityName;
/**
* Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to a Service Bus entity.
*/
ServiceBusSenderAsyncClient(String entityName, MessagingEntityType entityType,
ServiceBusConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider,
MessageSerializer messageSerializer, Runnable onClientClose, String viaEntityName) {
this.messageSerializer = Objects.requireNonNull(messageSerializer,
"'messageSerializer' cannot be null.");
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null.");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor,
"'connectionProcessor' cannot be null.");
this.tracerProvider = tracerProvider;
this.retryPolicy = getRetryPolicy(retryOptions);
this.entityType = entityType;
this.viaEntityName = viaEntityName;
this.onClientClose = onClientClose;
}
/**
* Gets the fully qualified namespace.
*
* @return The fully qualified namespace.
*/
public String getFullyQualifiedNamespace() {
return connectionProcessor.getFullyQualifiedNamespace();
}
/**
* Gets the name of the Service Bus resource.
*
* @return The name of the Service Bus resource.
*/
public String getEntityPath() {
return entityName;
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
*/
public Mono<Void> sendMessage(ServiceBusMessage message) {
if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
}
return sendInternal(Flux.just(message), null);
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
*/
public Mono<Void> sendMessage(ServiceBusMessage message, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(Flux.just(message), transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages
* exceed the maximum size of a single batch, an exception will be triggered and the send will fail.
* By default, the message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
* @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendIterable(messages, transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages exceed
* the maximum size of a single batch, an exception will be triggered and the send will fail. By default, the
* message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code messages} is {@code null}.
* @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages) {
return sendIterable(messages, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch} is {@code null}.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch) {
return sendInternal(batch, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(batch, transactionContext);
}
/**
* Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*
* @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*/
public Mono<ServiceBusMessageBatch> createBatch() {
return createBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link ServiceBusMessageBatch} configured with the options specified.
*
* @param options A set of options used to configure the {@link ServiceBusMessageBatch}.
*
* @return A new {@link ServiceBusMessageBatch} configured with the given options.
* @throws NullPointerException if {@code options} is null.
*/
public Mono<ServiceBusMessageBatch> createBatch(CreateBatchOptions options) {
if (Objects.isNull(options)) {
return monoError(logger, new NullPointerException("'options' cannot be null."));
}
final int maxSize = options.getMaximumSizeInBytes();
return getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (maxSize > maximumLinkSize) {
return monoError(logger, new IllegalArgumentException(String.format(Locale.US,
"CreateBatchOptions.getMaximumSizeInBytes (%s bytes) is larger than the link size"
+ " (%s bytes).", maxSize, maximumLinkSize)));
}
final int batchSize = maxSize > 0
? maxSize
: maximumLinkSize;
return Mono.just(
new ServiceBusMessageBatch(batchSize, link::getErrorContext, tracerProvider, messageSerializer,
entityName, getFullyQualifiedNamespace()));
}));
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message}, {@code scheduledEnqueueTime}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return scheduleMessageInternal(message, scheduledEnqueueTime, transactionContext);
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime) {
return scheduleMessageInternal(message, scheduledEnqueueTime, null);
}
/**
* Sends a scheduled messages to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param messages Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code messages} or {@code scheduledEnqueueTime} is {@code null}.
*/
public Flux<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime) {
return scheduleMessages(messages, scheduledEnqueueTime, null);
}
/**
* Sends a scheduled messages to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param messages Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime Instant at which the message should appear in the Service Bus queue or topic.
* @param transactionContext to be set on batch message before scheduling them on Service Bus.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}.
*/
public Flux<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(messages)) {
return fluxError(logger, new NullPointerException("'messages' cannot be null."));
}
if (Objects.isNull(scheduledEnqueueTime)) {
return fluxError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null."));
}
return createBatch().flatMapMany(messageBatch -> {
messages.forEach(message -> messageBatch.tryAdd(message));
return getSendLink().flatMapMany(link -> connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMapMany(managementNode -> managementNode.schedule(messageBatch.getMessages(), scheduledEnqueueTime,
messageBatch.getMaxSizeInBytes(), link.getLinkName(), transactionContext)));
});
}
/**
* Cancels the enqueuing of an already scheduled message, if it was not already enqueued.
*
* @param sequenceNumber of the scheduled message to cancel.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*
* @throws IllegalArgumentException if {@code sequenceNumber} is negative.
*/
public Mono<Void> cancelScheduledMessage(long sequenceNumber) {
if (sequenceNumber < 0) {
return monoError(logger, new IllegalArgumentException("'sequenceNumber' cannot be negative."));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.cancelScheduledMessages(Arrays.asList(sequenceNumber),
linkName.get()));
}
/**
* Cancels the enqueuing of an already scheduled message, if it was not already enqueued.
*
* @param sequenceNumbers of the scheduled messages to cancel.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code sequenceNumbers} is null.
*/
public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "cancelScheduledMessages")));
}
if (Objects.isNull(sequenceNumbers)) {
return monoError(logger, new NullPointerException("'messages' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.cancelScheduledMessages(sequenceNumbers, linkName.get()));
}
/**
* Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along with
* {@link ServiceBusReceivedMessage} or {@code lockToken } to all operations that needs to be in
* this transaction.
*
* @return a new {@link ServiceBusTransactionContext}.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the {@link ServiceBusSenderAsyncClient}. If the client had a dedicated connection, the underlying
* connection is also closed.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
onClientClose.run();
}
private Mono<Void> sendIterable(Iterable<ServiceBusMessage> messages, ServiceBusTransactionContext transaction) {
if (Objects.isNull(messages)) {
return monoError(logger, new NullPointerException("'messages' cannot be null."));
}
return createBatch().flatMap(messageBatch -> {
messages.forEach(message -> messageBatch.tryAdd(message));
return sendInternal(messageBatch, transaction);
});
}
private Mono<Long> scheduleMessageInternal(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
}
if (Objects.isNull(scheduledEnqueueTime)) {
return monoError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null."));
}
return getSendLink()
.flatMap(link -> link.getLinkSize().flatMap(size -> {
int maxSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.schedule(Arrays.asList(message), scheduledEnqueueTime,
maxSize, link.getLinkName(), transactionContext)
.next());
}));
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*/
private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages, ServiceBusTransactionContext transactionContext) {
return getSendLink()
.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final CreateBatchOptions batchOptions = new CreateBatchOptions()
.setMaximumSizeInBytes(batchSize);
return messages.collect(new AmqpMessageCollector(batchOptions, 1,
link::getErrorContext, tracerProvider, messageSerializer, entityName,
link.getHostname()));
})
.flatMap(list -> sendInternalBatch(Flux.fromIterable(list), transactionContext)));
}
private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches,
ServiceBusTransactionContext transactionContext) {
return eventBatches
.flatMap(messageBatch -> sendInternal(messageBatch, transactionContext))
.then()
.doOnError(error -> logger.error("Error sending batch.", error));
}
private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions,
entityName);
} else {
return connection.createSendLink(entityName, entityName, retryOptions, null);
}
})
.doOnNext(next -> linkName.compareAndSet(null, next.getLinkName()));
}
private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>,
List<ServiceBusMessageBatch>> {
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private final TracerProvider tracerProvider;
private final MessageSerializer serializer;
private final String entityPath;
private final String hostname;
private volatile ServiceBusMessageBatch currentBatch;
AmqpMessageCollector(CreateBatchOptions options, Integer maxNumberOfBatches,
ErrorContextProvider contextProvider, TracerProvider tracerProvider, MessageSerializer serializer,
String entityPath, String hostname) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.contextProvider = contextProvider;
this.tracerProvider = tracerProvider;
this.serializer = serializer;
this.entityPath = entityPath;
this.hostname = hostname;
currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer,
entityPath, hostname);
}
@Override
public Supplier<List<ServiceBusMessageBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() {
return (list, event) -> {
ServiceBusMessageBatch batch = currentBatch;
if (batch.tryAdd(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer,
entityPath, hostname);
currentBatch.tryAdd(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<ServiceBusMessageBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() {
return list -> {
ServiceBusMessageBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
} |
There is an `entityName` you can use for `entityPath`. I'm sure fullyqualifedDomainName is also exposed in this class. | private Mono<Void> sendInternal(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(batch)) {
return monoError(logger, new NullPointerException("'batch' cannot be null."));
}
final boolean isTracingEnabled = tracerProvider.isEnabled();
final AtomicReference<Context> parentContext = isTracingEnabled
? new AtomicReference<>(Context.NONE)
: null;
if (batch.getMessages().isEmpty()) {
logger.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
logger.info("Sending batch with size[{}].", batch.getCount());
Context sharedContext = null;
final List<org.apache.qpid.proton.message.Message> messages = new ArrayList<>();
for (int i = 0; i < batch.getMessages().size(); i++) {
final ServiceBusMessage event = batch.getMessages().get(i);
if (isTracingEnabled) {
parentContext.set(event.getContext());
if (i == 0) {
sharedContext = tracerProvider.getSharedSpanBuilder(parentContext.get());
}
tracerProvider.addSpanLinks(sharedContext.addData(SPAN_CONTEXT_KEY, event.getContext()));
}
final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(event);
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
message.setMessageAnnotations(messageAnnotations);
messages.add(message);
}
if (isTracingEnabled) {
final Context finalSharedContext = sharedContext == null
? Context.NONE
: sharedContext
.addData(ENTITY_PATH_KEY, "entityPath")
.addData(HOST_NAME_KEY, "hostName")
.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE);
parentContext.set(tracerProvider.startSpan(finalSharedContext, ProcessKind.SEND));
}
return withRetry(
getSendLink().flatMap(link -> {
if (transactionContext != null && transactionContext.getTransactionId() != null) {
final TransactionalState deliveryState = new TransactionalState();
deliveryState.setTxnId(new Binary(transactionContext.getTransactionId().array()));
return messages.size() == 1
? link.send(messages.get(0), deliveryState)
: link.send(messages, deliveryState);
} else {
return messages.size() == 1
? link.send(messages.get(0))
: link.send(messages);
}
})
.doOnEach(signal -> {
if (isTracingEnabled) {
tracerProvider.endSpan(parentContext.get(), signal);
}
})
.doOnError(error -> {
if (isTracingEnabled) {
tracerProvider.endSpan(parentContext.get(), Signal.error(error));
}
}), retryOptions.getTryTimeout(), retryPolicy);
} | .addData(HOST_NAME_KEY, "hostName") | private Mono<Void> sendInternal(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(batch)) {
return monoError(logger, new NullPointerException("'batch' cannot be null."));
}
final boolean isTracingEnabled = tracerProvider.isEnabled();
final AtomicReference<Context> parentContext = isTracingEnabled
? new AtomicReference<>(Context.NONE)
: null;
if (batch.getMessages().isEmpty()) {
logger.info("Cannot send an EventBatch that is empty.");
return Mono.empty();
}
logger.info("Sending batch with size[{}].", batch.getCount());
Context sharedContext = null;
final List<org.apache.qpid.proton.message.Message> messages = new ArrayList<>();
for (int i = 0; i < batch.getMessages().size(); i++) {
final ServiceBusMessage event = batch.getMessages().get(i);
if (isTracingEnabled) {
parentContext.set(event.getContext());
if (i == 0) {
sharedContext = tracerProvider.getSharedSpanBuilder(SERVICE_BASE_NAME, parentContext.get());
}
tracerProvider.addSpanLinks(sharedContext.addData(SPAN_CONTEXT_KEY, event.getContext()));
}
final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(event);
final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null
? new MessageAnnotations(new HashMap<>())
: message.getMessageAnnotations();
message.setMessageAnnotations(messageAnnotations);
messages.add(message);
}
if (isTracingEnabled) {
final Context finalSharedContext = sharedContext == null
? Context.NONE
: sharedContext
.addData(ENTITY_PATH_KEY, entityName)
.addData(HOST_NAME_KEY, connectionProcessor.getFullyQualifiedNamespace())
.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE);
parentContext.set(tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, finalSharedContext, ProcessKind.SEND));
}
return withRetry(
getSendLink().flatMap(link -> {
if (transactionContext != null && transactionContext.getTransactionId() != null) {
final TransactionalState deliveryState = new TransactionalState();
deliveryState.setTxnId(new Binary(transactionContext.getTransactionId().array()));
return messages.size() == 1
? link.send(messages.get(0), deliveryState)
: link.send(messages, deliveryState);
} else {
return messages.size() == 1
? link.send(messages.get(0))
: link.send(messages);
}
}), retryOptions.getTryTimeout(), retryPolicy)
.doOnEach(signal -> {
if (isTracingEnabled) {
tracerProvider.endSpan(parentContext.get(), signal);
}
});
} | class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final String AZ_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions();
private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class);
private final AtomicReference<String> linkName = new AtomicReference<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final AmqpRetryOptions retryOptions;
private final AmqpRetryPolicy retryPolicy;
private final MessagingEntityType entityType;
private final Runnable onClientClose;
private final String entityName;
private final ServiceBusConnectionProcessor connectionProcessor;
private final String viaEntityName;
/**
* Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to a Service Bus entity.
*/
ServiceBusSenderAsyncClient(String entityName, MessagingEntityType entityType,
ServiceBusConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider,
MessageSerializer messageSerializer, Runnable onClientClose, String viaEntityName) {
this.messageSerializer = Objects.requireNonNull(messageSerializer,
"'messageSerializer' cannot be null.");
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null.");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor,
"'connectionProcessor' cannot be null.");
this.tracerProvider = tracerProvider;
this.retryPolicy = getRetryPolicy(retryOptions);
this.entityType = entityType;
this.viaEntityName = viaEntityName;
this.onClientClose = onClientClose;
}
/**
* Gets the fully qualified namespace.
*
* @return The fully qualified namespace.
*/
public String getFullyQualifiedNamespace() {
return connectionProcessor.getFullyQualifiedNamespace();
}
/**
* Gets the name of the Service Bus resource.
*
* @return The name of the Service Bus resource.
*/
public String getEntityPath() {
return entityName;
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
*/
public Mono<Void> sendMessage(ServiceBusMessage message) {
if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
}
return sendInternal(Flux.just(message), null);
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
*/
public Mono<Void> sendMessage(ServiceBusMessage message, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(Flux.just(message), transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages
* exceed the maximum size of a single batch, an exception will be triggered and the send will fail.
* By default, the message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
* @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendIterable(messages, transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages exceed
* the maximum size of a single batch, an exception will be triggered and the send will fail. By default, the
* message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code messages} is {@code null}.
* @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages) {
return sendIterable(messages, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch} is {@code null}.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch) {
return sendInternal(batch, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(batch, transactionContext);
}
/**
* Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*
* @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*/
public Mono<ServiceBusMessageBatch> createBatch() {
return createBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link ServiceBusMessageBatch} configured with the options specified.
*
* @param options A set of options used to configure the {@link ServiceBusMessageBatch}.
*
* @return A new {@link ServiceBusMessageBatch} configured with the given options.
* @throws NullPointerException if {@code options} is null.
*/
public Mono<ServiceBusMessageBatch> createBatch(CreateBatchOptions options) {
if (Objects.isNull(options)) {
return monoError(logger, new NullPointerException("'options' cannot be null."));
}
final int maxSize = options.getMaximumSizeInBytes();
return getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (maxSize > maximumLinkSize) {
return monoError(logger, new IllegalArgumentException(String.format(Locale.US,
"CreateBatchOptions.getMaximumSizeInBytes (%s bytes) is larger than the link size"
+ " (%s bytes).", maxSize, maximumLinkSize)));
}
final int batchSize = maxSize > 0
? maxSize
: maximumLinkSize;
return Mono.just(
new ServiceBusMessageBatch(batchSize, link::getErrorContext, tracerProvider, messageSerializer));
}));
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message}, {@code scheduledEnqueueTime}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return scheduleMessageInternal(message, scheduledEnqueueTime, transactionContext);
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime) {
return scheduleMessageInternal(message, scheduledEnqueueTime, null);
}
/**
* Cancels the enqueuing of an already scheduled message, if it was not already enqueued.
*
* @param sequenceNumber of the scheduled message to cancel.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*
* @throws IllegalArgumentException if {@code sequenceNumber} is negative.
*/
public Mono<Void> cancelScheduledMessage(long sequenceNumber) {
if (sequenceNumber < 0) {
return monoError(logger, new IllegalArgumentException("'sequenceNumber' cannot be negative."));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.cancelScheduledMessage(sequenceNumber, linkName.get()));
}
/**
* Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along with
* {@link ServiceBusReceivedMessage} or {@code lockToken } to all operations that needs to be in
* this transaction.
*
* @return a new {@link ServiceBusTransactionContext}.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the {@link ServiceBusSenderAsyncClient}. If the client had a dedicated connection, the underlying
* connection is also closed.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
onClientClose.run();
}
private Mono<Void> sendIterable(Iterable<ServiceBusMessage> messages, ServiceBusTransactionContext transaction) {
if (Objects.isNull(messages)) {
return monoError(logger, new NullPointerException("'messages' cannot be null."));
}
return createBatch().flatMap(messageBatch -> {
messages.forEach(message -> messageBatch.tryAdd(message));
return sendInternal(messageBatch, transaction);
});
}
private Mono<Long> scheduleMessageInternal(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
}
if (Objects.isNull(scheduledEnqueueTime)) {
return monoError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null."));
}
return getSendLink()
.flatMap(link -> link.getLinkSize().flatMap(size -> {
int maxSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.schedule(message, scheduledEnqueueTime, maxSize,
link.getLinkName(), transactionContext));
}));
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*/
private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages, ServiceBusTransactionContext transactionContext) {
return getSendLink()
.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final CreateBatchOptions batchOptions = new CreateBatchOptions()
.setMaximumSizeInBytes(batchSize);
return messages.collect(new AmqpMessageCollector(batchOptions, 1,
link::getErrorContext, tracerProvider, messageSerializer));
})
.flatMap(list -> sendInternalBatch(Flux.fromIterable(list), transactionContext)));
}
private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches,
ServiceBusTransactionContext transactionContext) {
return eventBatches
.flatMap(messageBatch -> sendInternal(messageBatch, transactionContext))
.then()
.doOnError(error -> logger.error("Error sending batch.", error));
}
private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions,
entityName);
} else {
return connection.createSendLink(entityName, entityName, retryOptions, null);
}
})
.doOnNext(next -> linkName.compareAndSet(null, next.getLinkName()));
}
private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>,
List<ServiceBusMessageBatch>> {
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private final TracerProvider tracerProvider;
private final MessageSerializer serializer;
private volatile ServiceBusMessageBatch currentBatch;
AmqpMessageCollector(CreateBatchOptions options, Integer maxNumberOfBatches,
ErrorContextProvider contextProvider, TracerProvider tracerProvider, MessageSerializer serializer) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.contextProvider = contextProvider;
this.tracerProvider = tracerProvider;
this.serializer = serializer;
currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer);
}
@Override
public Supplier<List<ServiceBusMessageBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() {
return (list, event) -> {
ServiceBusMessageBatch batch = currentBatch;
if (batch.tryAdd(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer);
currentBatch.tryAdd(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<ServiceBusMessageBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() {
return list -> {
ServiceBusMessageBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
} | class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final String AZ_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions();
private static final String SERVICE_BASE_NAME = "ServiceBus.";
private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class);
private final AtomicReference<String> linkName = new AtomicReference<>();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final AmqpRetryOptions retryOptions;
private final AmqpRetryPolicy retryPolicy;
private final MessagingEntityType entityType;
private final Runnable onClientClose;
private final String entityName;
private final ServiceBusConnectionProcessor connectionProcessor;
private final String viaEntityName;
/**
* Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to a Service Bus entity.
*/
ServiceBusSenderAsyncClient(String entityName, MessagingEntityType entityType,
ServiceBusConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider,
MessageSerializer messageSerializer, Runnable onClientClose, String viaEntityName) {
this.messageSerializer = Objects.requireNonNull(messageSerializer,
"'messageSerializer' cannot be null.");
this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null.");
this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null.");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor,
"'connectionProcessor' cannot be null.");
this.tracerProvider = tracerProvider;
this.retryPolicy = getRetryPolicy(retryOptions);
this.entityType = entityType;
this.viaEntityName = viaEntityName;
this.onClientClose = onClientClose;
}
/**
* Gets the fully qualified namespace.
*
* @return The fully qualified namespace.
*/
public String getFullyQualifiedNamespace() {
return connectionProcessor.getFullyQualifiedNamespace();
}
/**
* Gets the name of the Service Bus resource.
*
* @return The name of the Service Bus resource.
*/
public String getEntityPath() {
return entityName;
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
*/
public Mono<Void> sendMessage(ServiceBusMessage message) {
if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
}
return sendInternal(Flux.just(message), null);
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return The {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code message} is {@code null}.
*/
public Mono<Void> sendMessage(ServiceBusMessage message, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(Flux.just(message), transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages
* exceed the maximum size of a single batch, an exception will be triggered and the send will fail.
* By default, the message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
* @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendIterable(messages, transactionContext);
}
/**
* Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages exceed
* the maximum size of a single batch, an exception will be triggered and the send will fail. By default, the
* message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
*
* @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource.
*
* @throws NullPointerException if {@code messages} is {@code null}.
* @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch.
*/
public Mono<Void> sendMessages(Iterable<ServiceBusMessage> messages) {
return sendIterable(messages, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch} is {@code null}.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch) {
return sendInternal(batch, null);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
*/
public Mono<Void> sendMessages(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return sendInternal(batch, transactionContext);
}
/**
* Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*
* @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*/
public Mono<ServiceBusMessageBatch> createBatch() {
return createBatch(DEFAULT_BATCH_OPTIONS);
}
/**
* Creates an {@link ServiceBusMessageBatch} configured with the options specified.
*
* @param options A set of options used to configure the {@link ServiceBusMessageBatch}.
*
* @return A new {@link ServiceBusMessageBatch} configured with the given options.
* @throws NullPointerException if {@code options} is null.
*/
public Mono<ServiceBusMessageBatch> createBatch(CreateBatchOptions options) {
if (Objects.isNull(options)) {
return monoError(logger, new NullPointerException("'options' cannot be null."));
}
final int maxSize = options.getMaximumSizeInBytes();
return getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> {
final int maximumLinkSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
if (maxSize > maximumLinkSize) {
return monoError(logger, new IllegalArgumentException(String.format(Locale.US,
"CreateBatchOptions.getMaximumSizeInBytes (%s bytes) is larger than the link size"
+ " (%s bytes).", maxSize, maximumLinkSize)));
}
final int batchSize = maxSize > 0
? maxSize
: maximumLinkSize;
return Mono.just(
new ServiceBusMessageBatch(batchSize, link::getErrorContext, tracerProvider, messageSerializer,
entityName, getFullyQualifiedNamespace()));
}));
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message}, {@code scheduledEnqueueTime}, {@code transactionContext} or
* {@code transactionContext.transactionID} is {@code null}.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
}
if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return scheduleMessageInternal(message, scheduledEnqueueTime, transactionContext);
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}.
*/
public Mono<Long> scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime) {
return scheduleMessageInternal(message, scheduledEnqueueTime, null);
}
/**
* Sends a scheduled messages to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param messages Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code messages} or {@code scheduledEnqueueTime} is {@code null}.
*/
public Flux<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime) {
return scheduleMessages(messages, scheduledEnqueueTime, null);
}
/**
* Sends a scheduled messages to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param messages Message to be sent to the Service Bus Queue.
* @param scheduledEnqueueTime Instant at which the message should appear in the Service Bus queue or topic.
* @param transactionContext to be set on batch message before scheduling them on Service Bus.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}.
*/
public Flux<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(messages)) {
return fluxError(logger, new NullPointerException("'messages' cannot be null."));
}
if (Objects.isNull(scheduledEnqueueTime)) {
return fluxError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null."));
}
return createBatch().flatMapMany(messageBatch -> {
messages.forEach(message -> messageBatch.tryAdd(message));
return getSendLink().flatMapMany(link -> connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMapMany(managementNode -> managementNode.schedule(messageBatch.getMessages(), scheduledEnqueueTime,
messageBatch.getMaxSizeInBytes(), link.getLinkName(), transactionContext)));
});
}
/**
* Cancels the enqueuing of an already scheduled message, if it was not already enqueued.
*
* @param sequenceNumber of the scheduled message to cancel.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*
* @throws IllegalArgumentException if {@code sequenceNumber} is negative.
*/
public Mono<Void> cancelScheduledMessage(long sequenceNumber) {
if (sequenceNumber < 0) {
return monoError(logger, new IllegalArgumentException("'sequenceNumber' cannot be negative."));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.cancelScheduledMessages(Arrays.asList(sequenceNumber),
linkName.get()));
}
/**
* Cancels the enqueuing of an already scheduled message, if it was not already enqueued.
*
* @param sequenceNumbers of the scheduled messages to cancel.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*
* @throws NullPointerException if {@code sequenceNumbers} is null.
*/
public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "cancelScheduledMessages")));
}
if (Objects.isNull(sequenceNumbers)) {
return monoError(logger, new NullPointerException("'messages' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.cancelScheduledMessages(sequenceNumbers, linkName.get()));
}
/**
* Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along with
* {@link ServiceBusReceivedMessage} or {@code lockToken } to all operations that needs to be in
* this transaction.
*
* @return a new {@link ServiceBusTransactionContext}.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the {@link ServiceBusSenderAsyncClient}. If the client had a dedicated connection, the underlying
* connection is also closed.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
onClientClose.run();
}
private Mono<Void> sendIterable(Iterable<ServiceBusMessage> messages, ServiceBusTransactionContext transaction) {
if (Objects.isNull(messages)) {
return monoError(logger, new NullPointerException("'messages' cannot be null."));
}
return createBatch().flatMap(messageBatch -> {
messages.forEach(message -> messageBatch.tryAdd(message));
return sendInternal(messageBatch, transaction);
});
}
private Mono<Long> scheduleMessageInternal(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(message)) {
return monoError(logger, new NullPointerException("'message' cannot be null."));
}
if (Objects.isNull(scheduledEnqueueTime)) {
return monoError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null."));
}
return getSendLink()
.flatMap(link -> link.getLinkSize().flatMap(size -> {
int maxSize = size > 0
? size
: MAX_MESSAGE_LENGTH_BYTES;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityName, entityType))
.flatMap(managementNode -> managementNode.schedule(Arrays.asList(message), scheduledEnqueueTime,
maxSize, link.getLinkName(), transactionContext)
.next());
}));
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on batch message before sending to Service Bus.
*
* @return A {@link Mono} the finishes this operation on service bus resource.
*/
private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages, ServiceBusTransactionContext transactionContext) {
return getSendLink()
.flatMap(link -> link.getLinkSize()
.flatMap(size -> {
final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES;
final CreateBatchOptions batchOptions = new CreateBatchOptions()
.setMaximumSizeInBytes(batchSize);
return messages.collect(new AmqpMessageCollector(batchOptions, 1,
link::getErrorContext, tracerProvider, messageSerializer, entityName,
link.getHostname()));
})
.flatMap(list -> sendInternalBatch(Flux.fromIterable(list), transactionContext)));
}
private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches,
ServiceBusTransactionContext transactionContext) {
return eventBatches
.flatMap(messageBatch -> sendInternal(messageBatch, transactionContext))
.then()
.doOnError(error -> logger.error("Error sending batch.", error));
}
private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions,
entityName);
} else {
return connection.createSendLink(entityName, entityName, retryOptions, null);
}
})
.doOnNext(next -> linkName.compareAndSet(null, next.getLinkName()));
}
private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>,
List<ServiceBusMessageBatch>> {
private final int maxMessageSize;
private final Integer maxNumberOfBatches;
private final ErrorContextProvider contextProvider;
private final TracerProvider tracerProvider;
private final MessageSerializer serializer;
private final String entityPath;
private final String hostname;
private volatile ServiceBusMessageBatch currentBatch;
AmqpMessageCollector(CreateBatchOptions options, Integer maxNumberOfBatches,
ErrorContextProvider contextProvider, TracerProvider tracerProvider, MessageSerializer serializer,
String entityPath, String hostname) {
this.maxNumberOfBatches = maxNumberOfBatches;
this.maxMessageSize = options.getMaximumSizeInBytes() > 0
? options.getMaximumSizeInBytes()
: MAX_MESSAGE_LENGTH_BYTES;
this.contextProvider = contextProvider;
this.tracerProvider = tracerProvider;
this.serializer = serializer;
this.entityPath = entityPath;
this.hostname = hostname;
currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer,
entityPath, hostname);
}
@Override
public Supplier<List<ServiceBusMessageBatch>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() {
return (list, event) -> {
ServiceBusMessageBatch batch = currentBatch;
if (batch.tryAdd(event)) {
return;
}
if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) {
final String message = String.format(Locale.US,
"EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches);
throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message,
contextProvider.getErrorContext());
}
currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer,
entityPath, hostname);
currentBatch.tryAdd(event);
list.add(batch);
};
}
@Override
public BinaryOperator<List<ServiceBusMessageBatch>> combiner() {
return (existing, another) -> {
existing.addAll(another);
return existing;
};
}
@Override
public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() {
return list -> {
ServiceBusMessageBatch batch = currentBatch;
currentBatch = null;
if (batch != null) {
list.add(batch);
}
return list;
};
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
} |
Isn't null value a bug? Or when is it expected. | public RequestTimeoutException(String message, HttpHeaders headers, SocketAddress remoteAddress) {
super(message,
null,
HttpUtils.asMap(headers),
HttpConstants.StatusCodes.REQUEST_TIMEOUT,
remoteAddress != null
? remoteAddress.toString()
: null);
} | remoteAddress != null | public RequestTimeoutException(String message, HttpHeaders headers, SocketAddress remoteAddress) {
super(message,
null,
HttpUtils.asMap(headers),
HttpConstants.StatusCodes.REQUEST_TIMEOUT,
remoteAddress != null
? remoteAddress.toString()
: null);
} | class RequestTimeoutException extends CosmosException {
/**
* Instantiates a new Request timeout exception.
*/
public RequestTimeoutException() {
this(RMResources.RequestTimeout, null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param cosmosError the cosmos error
* @param lsn the lsn
* @param partitionKeyRangeId the partition key range id
* @param responseHeaders the response headers
*/
public RequestTimeoutException(CosmosError cosmosError, long lsn, String partitionKeyRangeId,
Map<String, String> responseHeaders) {
super(HttpConstants.StatusCodes.REQUEST_TIMEOUT, cosmosError, responseHeaders);
BridgeInternal.setLSN(this, lsn);
BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param requestUri the request uri
*/
public RequestTimeoutException(String message, URI requestUri) {
this(message, null, null, requestUri);
}
RequestTimeoutException(String message,
Exception innerException,
URI requestUri,
String localIpAddress) {
this(message(localIpAddress, message), innerException, null, requestUri);
}
RequestTimeoutException(Exception innerException) {
this(RMResources.Gone, innerException, (HttpHeaders) null, null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param headers the headers
* @param requestUrl the request url
*/
public RequestTimeoutException(String message, HttpHeaders headers, URI requestUrl) {
super(message,
null,
HttpUtils.asMap(headers),
HttpConstants.StatusCodes.REQUEST_TIMEOUT,
requestUrl != null
? requestUrl.toString()
: null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param headers the headers
* @param remoteAddress the remote address
*/
RequestTimeoutException(String message, HttpHeaders headers, String requestUriString) {
super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUriString);
}
RequestTimeoutException(String message,
Exception innerException,
HttpHeaders headers,
URI requestUrl) {
super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT,
requestUrl != null ? requestUrl.toString() : null);
}
private static String message(String localIP, String baseMessage) {
if (!Strings.isNullOrEmpty(localIP)) {
return String.format(
RMResources.ExceptionMessageAddIpAddress,
baseMessage,
localIP);
}
return baseMessage;
}
} | class RequestTimeoutException extends CosmosException {
/**
* Instantiates a new Request timeout exception.
*/
public RequestTimeoutException() {
this(RMResources.RequestTimeout, null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param cosmosError the cosmos error
* @param lsn the lsn
* @param partitionKeyRangeId the partition key range id
* @param responseHeaders the response headers
*/
public RequestTimeoutException(CosmosError cosmosError, long lsn, String partitionKeyRangeId,
Map<String, String> responseHeaders) {
super(HttpConstants.StatusCodes.REQUEST_TIMEOUT, cosmosError, responseHeaders);
BridgeInternal.setLSN(this, lsn);
BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param requestUri the request uri
*/
public RequestTimeoutException(String message, URI requestUri) {
this(message, null, null, requestUri);
}
RequestTimeoutException(String message,
Exception innerException,
URI requestUri,
String localIpAddress) {
this(message(localIpAddress, message), innerException, null, requestUri);
}
RequestTimeoutException(Exception innerException) {
this(RMResources.Gone, innerException, (HttpHeaders) null, null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param headers the headers
* @param requestUrl the request url
*/
public RequestTimeoutException(String message, HttpHeaders headers, URI requestUrl) {
super(message,
null,
HttpUtils.asMap(headers),
HttpConstants.StatusCodes.REQUEST_TIMEOUT,
requestUrl != null
? requestUrl.toString()
: null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param headers the headers
* @param remoteAddress the remote address
*/
RequestTimeoutException(String message, HttpHeaders headers, String requestUriString) {
super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUriString);
}
RequestTimeoutException(String message,
Exception innerException,
HttpHeaders headers,
URI requestUrl) {
super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT,
requestUrl != null ? requestUrl.toString() : null);
}
private static String message(String localIP, String baseMessage) {
if (!Strings.isNullOrEmpty(localIP)) {
return String.format(
RMResources.ExceptionMessageAddIpAddress,
baseMessage,
localIP);
}
return baseMessage;
}
} |
Do upstream retries fail these or retry? (not a blocker now) | public RntbdRequestRecord request(final RntbdRequestArgs args) {
this.throwIfClosed();
int concurrentRequestSnapshot = this.concurrentRequests.incrementAndGet();
if (concurrentRequestSnapshot > this.maxConcurrentRequests) {
return FailFastRntbdRequestRecord.createAndFailFast(
args,
concurrentRequestSnapshot,
concurrentRequests,
metrics,
remoteAddress);
}
this.lastRequestNanoTime.set(args.nanoTimeCreated());
final RntbdRequestRecord record = this.write(args);
record.whenComplete((response, error) -> {
this.concurrentRequests.decrementAndGet();
this.metrics.markComplete(record);
});
return record;
} | return FailFastRntbdRequestRecord.createAndFailFast( | public RntbdRequestRecord request(final RntbdRequestArgs args) {
this.throwIfClosed();
int concurrentRequestSnapshot = this.concurrentRequests.incrementAndGet();
if (concurrentRequestSnapshot > this.maxConcurrentRequests) {
try {
return FailFastRntbdRequestRecord.createAndFailFast(
args,
concurrentRequestSnapshot,
metrics,
remoteAddress);
}
finally {
concurrentRequests.decrementAndGet();
}
}
this.lastRequestNanoTime.set(args.nanoTimeCreated());
final RntbdRequestRecord record = this.write(args);
record.whenComplete((response, error) -> {
this.concurrentRequests.decrementAndGet();
this.metrics.markComplete(record);
});
return record;
} | class RntbdServiceEndpoint implements RntbdEndpoint {
private static final String TAG_NAME = RntbdServiceEndpoint.class.getSimpleName();
private static final long QUIET_PERIOD = 2_000_000_000L;
private static final AtomicLong instanceCount = new AtomicLong();
private static final Logger logger = LoggerFactory.getLogger(RntbdServiceEndpoint.class);
private static final AdaptiveRecvByteBufAllocator receiveBufferAllocator = new AdaptiveRecvByteBufAllocator();
private final RntbdClientChannelPool channelPool;
private final AtomicBoolean closed;
private final AtomicInteger concurrentRequests;
private final long id;
private final AtomicLong lastRequestNanoTime;
private final RntbdMetrics metrics;
private final Provider provider;
private final SocketAddress remoteAddress;
private final RntbdRequestTimer requestTimer;
private final Tag tag;
private final int maxConcurrentRequests;
private RntbdServiceEndpoint(
final Provider provider,
final Config config,
final NioEventLoopGroup group,
final RntbdRequestTimer timer,
final URI physicalAddress) {
final Bootstrap bootstrap = new Bootstrap()
.channel(NioSocketChannel.class)
.group(group)
.option(ChannelOption.ALLOCATOR, config.allocator())
.option(ChannelOption.AUTO_READ, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutInMillis())
.option(ChannelOption.RCVBUF_ALLOCATOR, receiveBufferAllocator)
.option(ChannelOption.SO_KEEPALIVE, true)
.remoteAddress(physicalAddress.getHost(), physicalAddress.getPort());
this.channelPool = new RntbdClientChannelPool(this, bootstrap, config);
this.remoteAddress = bootstrap.config().remoteAddress();
this.concurrentRequests = new AtomicInteger();
this.lastRequestNanoTime = new AtomicLong(System.nanoTime());
this.closed = new AtomicBoolean();
this.requestTimer = timer;
this.tag = Tag.of(TAG_NAME, RntbdMetrics.escape(this.remoteAddress.toString()));
this.id = instanceCount.incrementAndGet();
this.provider = provider;
this.metrics = new RntbdMetrics(provider.transportClient, this);
this.maxConcurrentRequests = config.maxConcurrentRequestsPerEndpoint();
}
/**
* @return approximate number of acquired channels.
*/
@Override
public int channelsAcquiredMetric() {
return this.channelPool.channelsAcquiredMetrics();
}
/**
* @return approximate number of available channels.
*/
@Override
public int channelsAvailableMetric() {
return this.channelPool.channelsAvailableMetrics();
}
@Override
public int concurrentRequests() {
return this.concurrentRequests.get();
}
@Override
public long id() {
return this.id;
}
@Override
public boolean isClosed() {
return this.closed.get();
}
public long lastRequestNanoTime() {
return this.lastRequestNanoTime.get();
}
@Override
public SocketAddress remoteAddress() {
return this.remoteAddress;
}
@Override
public int requestQueueLength() {
return this.channelPool.requestQueueLength();
}
@Override
public Tag tag() {
return this.tag;
}
@Override
public long usedDirectMemory() {
return this.channelPool.usedDirectMemory();
}
@Override
public long usedHeapMemory() {
return this.channelPool.usedHeapMemory();
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
this.provider.evict(this);
this.channelPool.close();
}
}
@Override
public String toString() {
return RntbdObjectMapper.toString(this);
}
private void ensureSuccessWhenReleasedToPool(Channel channel, Future<Void> released) {
if (released.isSuccess()) {
logger.debug("\n [{}]\n {}\n release succeeded", this, channel);
} else {
logger.debug("\n [{}]\n {}\n release failed due to {}", this, channel, released.cause());
}
}
private void releaseToPool(final Channel channel) {
logger.debug("\n [{}]\n {}\n RELEASE", this, channel);
final Future<Void> released = this.channelPool.release(channel);
if (logger.isDebugEnabled()) {
if (released.isDone()) {
ensureSuccessWhenReleasedToPool(channel, released);
} else {
released.addListener(ignored -> ensureSuccessWhenReleasedToPool(channel, released));
}
}
}
private void throwIfClosed() {
checkState(!this.closed.get(), "%s is closed", this);
}
private RntbdRequestRecord write(final RntbdRequestArgs requestArgs) {
final RntbdRequestRecord requestRecord = new AsyncRntbdRequestRecord(requestArgs, this.requestTimer);
final Future<Channel> connectedChannel = this.channelPool.acquire();
logger.debug("\n [{}]\n {}\n WRITE WHEN CONNECTED {}", this, requestArgs, connectedChannel);
if (connectedChannel.isDone()) {
return writeWhenConnected(requestRecord, connectedChannel);
} else {
connectedChannel.addListener(ignored -> writeWhenConnected(requestRecord, connectedChannel));
}
return requestRecord;
}
private RntbdRequestRecord writeWhenConnected(
final RntbdRequestRecord requestRecord, final Future<? super Channel> connected) {
if (connected.isSuccess()) {
final Channel channel = (Channel) connected.getNow();
assert channel != null : "impossible";
this.releaseToPool(channel);
channel.write(requestRecord.stage(RntbdRequestRecord.Stage.PIPELINED));
return requestRecord;
}
final RntbdRequestArgs requestArgs = requestRecord.args();
final UUID activityId = requestArgs.activityId();
final Throwable cause = connected.cause();
if (connected.isCancelled()) {
logger.debug("\n [{}]\n {}\n write cancelled: {}", this, requestArgs, cause);
requestRecord.cancel(true);
} else {
logger.debug("\n [{}]\n {}\n write failed due to {} ", this, requestArgs, cause);
final String reason = cause.toString();
final GoneException goneException = new GoneException(
lenientFormat("failed to establish connection to %s due to %s", this.remoteAddress, reason),
cause instanceof Exception ? (Exception) cause : new IOException(reason, cause),
ImmutableMap.of(HttpHeaders.ACTIVITY_ID, activityId.toString()),
requestArgs.replicaPath()
);
BridgeInternal.setRequestHeaders(goneException, requestArgs.serviceRequest().getHeaders());
requestRecord.completeExceptionally(goneException);
}
return requestRecord;
}
static final class JsonSerializer extends StdSerializer<RntbdServiceEndpoint> {
private static final long serialVersionUID = -5764954918168771152L;
public JsonSerializer() {
super(RntbdServiceEndpoint.class);
}
@Override
public void serialize(RntbdServiceEndpoint value, JsonGenerator generator, SerializerProvider provider)
throws IOException {
generator.writeStartObject();
generator.writeNumberField("id", value.id);
generator.writeBooleanField("isClosed", value.isClosed());
generator.writeNumberField("concurrentRequests", value.concurrentRequests());
generator.writeStringField("remoteAddress", value.remoteAddress.toString());
generator.writeObjectField("channelPool", value.channelPool);
generator.writeEndObject();
}
}
public static final class Provider implements RntbdEndpoint.Provider {
private static final Logger logger = LoggerFactory.getLogger(Provider.class);
private final AtomicBoolean closed;
private final Config config;
private final ConcurrentHashMap<String, RntbdEndpoint> endpoints;
private final NioEventLoopGroup eventLoopGroup;
private final AtomicInteger evictions;
private final RntbdRequestTimer requestTimer;
private final RntbdTransportClient transportClient;
public Provider(
final RntbdTransportClient transportClient,
final Options options,
final SslContext sslContext) {
checkNotNull(transportClient, "expected non-null provider");
checkNotNull(options, "expected non-null options");
checkNotNull(sslContext, "expected non-null sslContext");
final DefaultThreadFactory threadFactory = new DefaultThreadFactory("cosmos-rntbd-nio", true);
final LogLevel wireLogLevel;
if (logger.isDebugEnabled()) {
wireLogLevel = LogLevel.TRACE;
} else {
wireLogLevel = null;
}
this.transportClient = transportClient;
this.config = new Config(options, sslContext, wireLogLevel);
this.requestTimer = new RntbdRequestTimer(
config.requestTimeoutInNanos(),
config.requestTimerResolutionInNanos());
this.eventLoopGroup = new NioEventLoopGroup(options.threadCount(), threadFactory);
this.endpoints = new ConcurrentHashMap<>();
this.evictions = new AtomicInteger();
this.closed = new AtomicBoolean();
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
for (final RntbdEndpoint endpoint : this.endpoints.values()) {
endpoint.close();
}
this.eventLoopGroup.shutdownGracefully(QUIET_PERIOD, this.config.shutdownTimeoutInNanos(), NANOSECONDS)
.addListener(future -> {
this.requestTimer.close();
if (future.isSuccess()) {
logger.debug("\n [{}]\n closed endpoints", this);
return;
}
logger.error("\n [{}]\n failed to close endpoints due to ", this, future.cause());
});
return;
}
logger.debug("\n [{}]\n already closed", this);
}
@Override
public Config config() {
return this.config;
}
@Override
public int count() {
return this.endpoints.size();
}
@Override
public int evictions() {
return this.evictions.get();
}
@Override
public RntbdEndpoint get(final URI physicalAddress) {
return endpoints.computeIfAbsent(physicalAddress.getAuthority(), authority -> new RntbdServiceEndpoint(
this,
this.config,
this.eventLoopGroup,
this.requestTimer,
physicalAddress));
}
@Override
public Stream<RntbdEndpoint> list() {
return this.endpoints.values().stream();
}
private void evict(final RntbdEndpoint endpoint) {
if (this.endpoints.remove(endpoint.remoteAddress().toString()) != null) {
this.evictions.incrementAndGet();
}
}
}
} | class RntbdServiceEndpoint implements RntbdEndpoint {
private static final String TAG_NAME = RntbdServiceEndpoint.class.getSimpleName();
private static final long QUIET_PERIOD = 2_000_000_000L;
private static final AtomicLong instanceCount = new AtomicLong();
private static final Logger logger = LoggerFactory.getLogger(RntbdServiceEndpoint.class);
private static final AdaptiveRecvByteBufAllocator receiveBufferAllocator = new AdaptiveRecvByteBufAllocator();
private final RntbdClientChannelPool channelPool;
private final AtomicBoolean closed;
private final AtomicInteger concurrentRequests;
private final long id;
private final AtomicLong lastRequestNanoTime;
private final RntbdMetrics metrics;
private final Provider provider;
private final SocketAddress remoteAddress;
private final RntbdRequestTimer requestTimer;
private final Tag tag;
private final int maxConcurrentRequests;
private RntbdServiceEndpoint(
final Provider provider,
final Config config,
final NioEventLoopGroup group,
final RntbdRequestTimer timer,
final URI physicalAddress) {
final Bootstrap bootstrap = new Bootstrap()
.channel(NioSocketChannel.class)
.group(group)
.option(ChannelOption.ALLOCATOR, config.allocator())
.option(ChannelOption.AUTO_READ, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutInMillis())
.option(ChannelOption.RCVBUF_ALLOCATOR, receiveBufferAllocator)
.option(ChannelOption.SO_KEEPALIVE, true)
.remoteAddress(physicalAddress.getHost(), physicalAddress.getPort());
this.channelPool = new RntbdClientChannelPool(this, bootstrap, config);
this.remoteAddress = bootstrap.config().remoteAddress();
this.concurrentRequests = new AtomicInteger();
this.lastRequestNanoTime = new AtomicLong(System.nanoTime());
this.closed = new AtomicBoolean();
this.requestTimer = timer;
this.tag = Tag.of(TAG_NAME, RntbdMetrics.escape(this.remoteAddress.toString()));
this.id = instanceCount.incrementAndGet();
this.provider = provider;
this.metrics = new RntbdMetrics(provider.transportClient, this);
this.maxConcurrentRequests = config.maxConcurrentRequestsPerEndpoint();
}
/**
* @return approximate number of acquired channels.
*/
@Override
public int channelsAcquiredMetric() {
return this.channelPool.channelsAcquiredMetrics();
}
/**
* @return approximate number of available channels.
*/
@Override
public int channelsAvailableMetric() {
return this.channelPool.channelsAvailableMetrics();
}
@Override
public int concurrentRequests() {
return this.concurrentRequests.get();
}
@Override
public long id() {
return this.id;
}
@Override
public boolean isClosed() {
return this.closed.get();
}
public long lastRequestNanoTime() {
return this.lastRequestNanoTime.get();
}
@Override
public SocketAddress remoteAddress() {
return this.remoteAddress;
}
@Override
public int requestQueueLength() {
return this.channelPool.requestQueueLength();
}
@Override
public Tag tag() {
return this.tag;
}
@Override
public long usedDirectMemory() {
return this.channelPool.usedDirectMemory();
}
@Override
public long usedHeapMemory() {
return this.channelPool.usedHeapMemory();
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
this.provider.evict(this);
this.channelPool.close();
}
}
@Override
public String toString() {
return RntbdObjectMapper.toString(this);
}
private void ensureSuccessWhenReleasedToPool(Channel channel, Future<Void> released) {
if (released.isSuccess()) {
logger.debug("\n [{}]\n {}\n release succeeded", this, channel);
} else {
logger.debug("\n [{}]\n {}\n release failed due to {}", this, channel, released.cause());
}
}
private void releaseToPool(final Channel channel) {
logger.debug("\n [{}]\n {}\n RELEASE", this, channel);
final Future<Void> released = this.channelPool.release(channel);
if (logger.isDebugEnabled()) {
if (released.isDone()) {
ensureSuccessWhenReleasedToPool(channel, released);
} else {
released.addListener(ignored -> ensureSuccessWhenReleasedToPool(channel, released));
}
}
}
private void throwIfClosed() {
checkState(!this.closed.get(), "%s is closed", this);
}
private RntbdRequestRecord write(final RntbdRequestArgs requestArgs) {
final RntbdRequestRecord requestRecord = new AsyncRntbdRequestRecord(requestArgs, this.requestTimer);
final Future<Channel> connectedChannel = this.channelPool.acquire();
logger.debug("\n [{}]\n {}\n WRITE WHEN CONNECTED {}", this, requestArgs, connectedChannel);
if (connectedChannel.isDone()) {
return writeWhenConnected(requestRecord, connectedChannel);
} else {
connectedChannel.addListener(ignored -> writeWhenConnected(requestRecord, connectedChannel));
}
return requestRecord;
}
private RntbdRequestRecord writeWhenConnected(
final RntbdRequestRecord requestRecord, final Future<? super Channel> connected) {
if (connected.isSuccess()) {
final Channel channel = (Channel) connected.getNow();
assert channel != null : "impossible";
this.releaseToPool(channel);
channel.write(requestRecord.stage(RntbdRequestRecord.Stage.PIPELINED));
return requestRecord;
}
final RntbdRequestArgs requestArgs = requestRecord.args();
final UUID activityId = requestArgs.activityId();
final Throwable cause = connected.cause();
if (connected.isCancelled()) {
logger.debug("\n [{}]\n {}\n write cancelled: {}", this, requestArgs, cause);
requestRecord.cancel(true);
} else {
logger.debug("\n [{}]\n {}\n write failed due to {} ", this, requestArgs, cause);
final String reason = cause.toString();
final GoneException goneException = new GoneException(
lenientFormat("failed to establish connection to %s due to %s", this.remoteAddress, reason),
cause instanceof Exception ? (Exception) cause : new IOException(reason, cause),
ImmutableMap.of(HttpHeaders.ACTIVITY_ID, activityId.toString()),
requestArgs.replicaPath()
);
BridgeInternal.setRequestHeaders(goneException, requestArgs.serviceRequest().getHeaders());
requestRecord.completeExceptionally(goneException);
}
return requestRecord;
}
static final class JsonSerializer extends StdSerializer<RntbdServiceEndpoint> {
private static final long serialVersionUID = -5764954918168771152L;
public JsonSerializer() {
super(RntbdServiceEndpoint.class);
}
@Override
public void serialize(RntbdServiceEndpoint value, JsonGenerator generator, SerializerProvider provider)
throws IOException {
generator.writeStartObject();
generator.writeNumberField("id", value.id);
generator.writeBooleanField("isClosed", value.isClosed());
generator.writeNumberField("concurrentRequests", value.concurrentRequests());
generator.writeStringField("remoteAddress", value.remoteAddress.toString());
generator.writeObjectField("channelPool", value.channelPool);
generator.writeEndObject();
}
}
public static final class Provider implements RntbdEndpoint.Provider {
private static final Logger logger = LoggerFactory.getLogger(Provider.class);
private final AtomicBoolean closed;
private final Config config;
private final ConcurrentHashMap<String, RntbdEndpoint> endpoints;
private final NioEventLoopGroup eventLoopGroup;
private final AtomicInteger evictions;
private final RntbdRequestTimer requestTimer;
private final RntbdTransportClient transportClient;
public Provider(
final RntbdTransportClient transportClient,
final Options options,
final SslContext sslContext) {
checkNotNull(transportClient, "expected non-null provider");
checkNotNull(options, "expected non-null options");
checkNotNull(sslContext, "expected non-null sslContext");
final DefaultThreadFactory threadFactory = new DefaultThreadFactory("cosmos-rntbd-nio", true);
final LogLevel wireLogLevel;
if (logger.isDebugEnabled()) {
wireLogLevel = LogLevel.TRACE;
} else {
wireLogLevel = null;
}
this.transportClient = transportClient;
this.config = new Config(options, sslContext, wireLogLevel);
this.requestTimer = new RntbdRequestTimer(
config.requestTimeoutInNanos(),
config.requestTimerResolutionInNanos());
this.eventLoopGroup = new NioEventLoopGroup(options.threadCount(), threadFactory);
this.endpoints = new ConcurrentHashMap<>();
this.evictions = new AtomicInteger();
this.closed = new AtomicBoolean();
}
@Override
public void close() {
if (this.closed.compareAndSet(false, true)) {
for (final RntbdEndpoint endpoint : this.endpoints.values()) {
endpoint.close();
}
this.eventLoopGroup.shutdownGracefully(QUIET_PERIOD, this.config.shutdownTimeoutInNanos(), NANOSECONDS)
.addListener(future -> {
this.requestTimer.close();
if (future.isSuccess()) {
logger.debug("\n [{}]\n closed endpoints", this);
return;
}
logger.error("\n [{}]\n failed to close endpoints due to ", this, future.cause());
});
return;
}
logger.debug("\n [{}]\n already closed", this);
}
@Override
public Config config() {
return this.config;
}
@Override
public int count() {
return this.endpoints.size();
}
@Override
public int evictions() {
return this.evictions.get();
}
@Override
public RntbdEndpoint get(final URI physicalAddress) {
return endpoints.computeIfAbsent(physicalAddress.getAuthority(), authority -> new RntbdServiceEndpoint(
this,
this.config,
this.eventLoopGroup,
this.requestTimer,
physicalAddress));
}
@Override
public Stream<RntbdEndpoint> list() {
return this.endpoints.values().stream();
}
private void evict(final RntbdEndpoint endpoint) {
if (this.endpoints.remove(endpoint.remoteAddress().toString()) != null) {
this.evictions.incrementAndGet();
}
}
}
} |
Not expected - null check here to avoid NPE - and to be consistent with other overloads. So consumers of the RequestTimeoutException have to be aware that it can be null today already. Leaving it as is - please reactivate if you disagree. | public RequestTimeoutException(String message, HttpHeaders headers, SocketAddress remoteAddress) {
super(message,
null,
HttpUtils.asMap(headers),
HttpConstants.StatusCodes.REQUEST_TIMEOUT,
remoteAddress != null
? remoteAddress.toString()
: null);
} | remoteAddress != null | public RequestTimeoutException(String message, HttpHeaders headers, SocketAddress remoteAddress) {
super(message,
null,
HttpUtils.asMap(headers),
HttpConstants.StatusCodes.REQUEST_TIMEOUT,
remoteAddress != null
? remoteAddress.toString()
: null);
} | class RequestTimeoutException extends CosmosException {
/**
* Instantiates a new Request timeout exception.
*/
public RequestTimeoutException() {
this(RMResources.RequestTimeout, null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param cosmosError the cosmos error
* @param lsn the lsn
* @param partitionKeyRangeId the partition key range id
* @param responseHeaders the response headers
*/
public RequestTimeoutException(CosmosError cosmosError, long lsn, String partitionKeyRangeId,
Map<String, String> responseHeaders) {
super(HttpConstants.StatusCodes.REQUEST_TIMEOUT, cosmosError, responseHeaders);
BridgeInternal.setLSN(this, lsn);
BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param requestUri the request uri
*/
public RequestTimeoutException(String message, URI requestUri) {
this(message, null, null, requestUri);
}
RequestTimeoutException(String message,
Exception innerException,
URI requestUri,
String localIpAddress) {
this(message(localIpAddress, message), innerException, null, requestUri);
}
RequestTimeoutException(Exception innerException) {
this(RMResources.Gone, innerException, (HttpHeaders) null, null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param headers the headers
* @param requestUrl the request url
*/
public RequestTimeoutException(String message, HttpHeaders headers, URI requestUrl) {
super(message,
null,
HttpUtils.asMap(headers),
HttpConstants.StatusCodes.REQUEST_TIMEOUT,
requestUrl != null
? requestUrl.toString()
: null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param headers the headers
* @param remoteAddress the remote address
*/
RequestTimeoutException(String message, HttpHeaders headers, String requestUriString) {
super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUriString);
}
RequestTimeoutException(String message,
Exception innerException,
HttpHeaders headers,
URI requestUrl) {
super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT,
requestUrl != null ? requestUrl.toString() : null);
}
private static String message(String localIP, String baseMessage) {
if (!Strings.isNullOrEmpty(localIP)) {
return String.format(
RMResources.ExceptionMessageAddIpAddress,
baseMessage,
localIP);
}
return baseMessage;
}
} | class RequestTimeoutException extends CosmosException {
/**
* Instantiates a new Request timeout exception.
*/
public RequestTimeoutException() {
this(RMResources.RequestTimeout, null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param cosmosError the cosmos error
* @param lsn the lsn
* @param partitionKeyRangeId the partition key range id
* @param responseHeaders the response headers
*/
public RequestTimeoutException(CosmosError cosmosError, long lsn, String partitionKeyRangeId,
Map<String, String> responseHeaders) {
super(HttpConstants.StatusCodes.REQUEST_TIMEOUT, cosmosError, responseHeaders);
BridgeInternal.setLSN(this, lsn);
BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param requestUri the request uri
*/
public RequestTimeoutException(String message, URI requestUri) {
this(message, null, null, requestUri);
}
RequestTimeoutException(String message,
Exception innerException,
URI requestUri,
String localIpAddress) {
this(message(localIpAddress, message), innerException, null, requestUri);
}
RequestTimeoutException(Exception innerException) {
this(RMResources.Gone, innerException, (HttpHeaders) null, null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param headers the headers
* @param requestUrl the request url
*/
public RequestTimeoutException(String message, HttpHeaders headers, URI requestUrl) {
super(message,
null,
HttpUtils.asMap(headers),
HttpConstants.StatusCodes.REQUEST_TIMEOUT,
requestUrl != null
? requestUrl.toString()
: null);
}
/**
* Instantiates a new Request timeout exception.
*
* @param message the message
* @param headers the headers
* @param remoteAddress the remote address
*/
RequestTimeoutException(String message, HttpHeaders headers, String requestUriString) {
super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUriString);
}
RequestTimeoutException(String message,
Exception innerException,
HttpHeaders headers,
URI requestUrl) {
super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT,
requestUrl != null ? requestUrl.toString() : null);
}
private static String message(String localIP, String baseMessage) {
if (!Strings.isNullOrEmpty(localIP)) {
return String.format(
RMResources.ExceptionMessageAddIpAddress,
baseMessage,
localIP);
}
return baseMessage;
}
} |
Same here, should we check whether the logger.isDebugEnabled? | private void acquireChannel(final ChannelPromiseWithExpiryTime promise) {
this.ensureInEventLoop();
if (this.isClosed()) {
promise.setFailure(POOL_CLOSED_ON_ACQUIRE);
return;
}
try {
Channel candidate = this.pollChannel();
if (candidate != null) {
doAcquireChannel(promise, candidate);
return;
}
final int channelCount = this.channels(false);
if (channelCount < this.maxChannels) {
if (this.connecting.compareAndSet(false, true)) {
final Promise<Channel> anotherPromise = this.newChannelPromiseForToBeEstablishedChannel(promise);
final ChannelFuture future = this.bootstrap.clone().attr(POOL_KEY, this).connect();
if (future.isDone()) {
this.safeNotifyChannelConnect(future, anotherPromise);
} else {
future.addListener(ignored -> this.safeNotifyChannelConnect(future, anotherPromise));
}
return;
}
} else if (this.computeLoadFactor() > 0.90D) {
long pendingRequestCountMin = Long.MAX_VALUE;
for (Channel channel : this.availableChannels) {
final RntbdRequestManager manager = channel.pipeline().get(RntbdRequestManager.class);
if (manager == null) {
logger.debug("Channel({} --> {}) closed", channel, this.remoteAddress());
} else {
final long pendingRequestCount = manager.pendingRequestCount();
if (pendingRequestCount < pendingRequestCountMin && isChannelServiceable(channel)) {
pendingRequestCountMin = pendingRequestCount;
candidate = channel;
}
}
}
if (candidate != null && this.availableChannels.remove(candidate)) {
this.doAcquireChannel(promise, candidate);
return;
}
} else {
for (Channel channel : this.availableChannels) {
if (isChannelServiceable(channel)) {
if (this.availableChannels.remove(channel)) {
this.doAcquireChannel(promise, channel);
return;
}
}
}
}
this.addTaskToPendingAcquisitionQueue(promise);
} catch (Throwable cause) {
promise.tryFailure(cause);
}
} | logger.debug("Channel({} --> {}) closed", channel, this.remoteAddress()); | private void acquireChannel(final ChannelPromiseWithExpiryTime promise) {
this.ensureInEventLoop();
if (this.isClosed()) {
promise.setFailure(POOL_CLOSED_ON_ACQUIRE);
return;
}
try {
Channel candidate = this.pollChannel();
if (candidate != null) {
doAcquireChannel(promise, candidate);
return;
}
final int channelCount = this.channels(false);
if (channelCount < this.maxChannels) {
if (this.connecting.compareAndSet(false, true)) {
final Promise<Channel> anotherPromise = this.newChannelPromiseForToBeEstablishedChannel(promise);
final ChannelFuture future = this.bootstrap.clone().attr(POOL_KEY, this).connect();
if (future.isDone()) {
this.safeNotifyChannelConnect(future, anotherPromise);
} else {
future.addListener(ignored -> this.safeNotifyChannelConnect(future, anotherPromise));
}
return;
}
} else if (this.computeLoadFactor() > 0.90D) {
long pendingRequestCountMin = Long.MAX_VALUE;
for (Channel channel : this.availableChannels) {
final RntbdRequestManager manager = channel.pipeline().get(RntbdRequestManager.class);
if (manager == null) {
logger.debug("Channel({} --> {}) closed", channel, this.remoteAddress());
} else {
final long pendingRequestCount = manager.pendingRequestCount();
if (pendingRequestCount < pendingRequestCountMin && isChannelServiceable(channel)) {
pendingRequestCountMin = pendingRequestCount;
candidate = channel;
}
}
}
if (candidate != null && this.availableChannels.remove(candidate)) {
this.doAcquireChannel(promise, candidate);
return;
}
} else {
for (Channel channel : this.availableChannels) {
if (isChannelServiceable(channel)) {
if (this.availableChannels.remove(channel)) {
this.doAcquireChannel(promise, channel);
return;
}
}
}
}
this.addTaskToPendingAcquisitionQueue(promise);
} catch (Throwable cause) {
promise.tryFailure(cause);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireListener channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireListener task) {
task.originalPromise.setFailure(ACQUISITION_TIMEOUT);
}
} | class and should be pulled up to RntbdServiceEndpoint or
this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos();
this.allocatorMetric = config.allocator().metric();
this.maxChannels = config.maxChannelsPerEndpoint();
this.maxRequestsPerChannel = config.maxRequestsPerChannel();
this.maxPendingAcquisitions = Integer.MAX_VALUE;
this.releaseHealthCheck = true;
this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) {
/**
* Fails a request due to a channel acquisition timeout.
*
* @param task a {@link AcquireListener channel acquisition task} that has timed out.
*/
@Override
public void onTimeout(AcquireListener task) {
task.originalPromise.setFailure(ACQUISITION_TIMEOUT);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.