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
Would `lastIndexOf` be a better indicator as there shouldn't be multiple end of blocks at once given the current design.
private static boolean isEndOfBlock(StringBuilder sb) { return sb.indexOf("\n\n") >= 0; }
return sb.indexOf("\n\n") >= 0;
private static boolean isEndOfBlock(StringBuilder sb) { return sb.lastIndexOf("\n\n") >= 0; }
class ServerSentEventUtil { private static final String DEFAULT_EVENT = "message"; private static final Pattern DIGITS_ONLY = Pattern.compile("^[\\d]*$"); private static final String LAST_EVENT_ID = "Last-Event-Id"; public static final String NO_LISTENER_LOG_MESSAGE = "No listener attached to the server sent event http request." + " Treating response as regular response."; /** * Processes the sse buffer and dispatches the event * * @param reader The BufferedReader object * @param listener The listener object attached with the httpRequest */ public static RetrySSEResult processBuffer(BufferedReader reader, ServerSentEventListener listener) { StringBuilder collectedData = new StringBuilder(); ServerSentEvent event = null; try { String line; while ((line = reader.readLine()) != null) { collectedData.append(line).append("\n"); if (isEndOfBlock(collectedData)) { event = processLines(collectedData.toString().split("\n")); if (!Objects.equals(event.getEvent(), DEFAULT_EVENT) || event.getData() != null) { listener.onEvent(event); } collectedData = new StringBuilder(); } } listener.onClose(); } catch (IOException e) { return new RetrySSEResult(e, event != null ? event.getId() : -1, event != null ? ServerSentEventHelper.getRetryAfter(event) : null); } return null; } /** * Retries the request if the listener allows it * * @param retrySSEResult the result of the retry * @param listener The listener object attached with the httpRequest * @param httpRequest the HTTP Request being sent */ public static boolean retryExceptionForSSE(RetrySSEResult retrySSEResult, ServerSentEventListener listener, HttpRequest httpRequest) { if (Thread.currentThread().isInterrupted() || !listener.shouldRetry(retrySSEResult.getException(), retrySSEResult.getRetryAfter(), retrySSEResult.getLastEventId())) { listener.onError(retrySSEResult.getException()); return true; } if (retrySSEResult.getLastEventId() != -1) { httpRequest.getHeaders() .add(HeaderName.fromString(LAST_EVENT_ID), String.valueOf(retrySSEResult.getLastEventId())); } try { if (retrySSEResult.getRetryAfter() != null) { Thread.sleep(retrySSEResult.getRetryAfter().toMillis()); } } catch (InterruptedException ignored) { return true; } return false; } private static ServerSentEvent processLines(String[] lines) { List<String> eventData = null; ServerSentEvent event = new ServerSentEvent(); for (String line : lines) { int idx = line.indexOf(':'); if (idx == 0) { ServerSentEventHelper.setComment(event, line.substring(1).trim()); continue; } String field = line.substring(0, idx < 0 ? lines.length : idx).trim().toLowerCase(); String value = idx < 0 ? "" : line.substring(idx + 1).trim(); switch (field) { case "event": ServerSentEventHelper.setEvent(event, value); break; case "data": if(eventData == null) { eventData = new ArrayList<>(); } eventData.add(value); break; case "id": if (!value.isEmpty()) { ServerSentEventHelper.setId(event, Long.parseLong(value)); } break; case "retry": if (!value.isEmpty() && DIGITS_ONLY.matcher(value).matches()) { ServerSentEventHelper.setRetryAfter(event, Duration.ofMillis(Long.parseLong(value))); } break; default: throw new IllegalArgumentException("Invalid data received from server"); } } if (event.getEvent() == null) { ServerSentEventHelper.setEvent(event, DEFAULT_EVENT); } if (eventData != null) { ServerSentEventHelper.setData(event, eventData); } return event; } }
class ServerSentEventUtil { private static final String DEFAULT_EVENT = "message"; private static final Pattern DIGITS_ONLY = Pattern.compile("^[\\d]*$"); private static final String LAST_EVENT_ID = "Last-Event-Id"; public static final String NO_LISTENER_ERROR_MESSAGE = "No ServerSentEventListener attached to HttpRequest to " + "handle the text/event-stream response"; private ServerSentEventUtil() { } /** * Checks if the content type is a text event stream * * @param contentType The content type * @return True if the content type is a text event stream */ public static boolean isTextEventStreamContentType(String contentType) { if (contentType != null) { return ContentType.TEXT_EVENT_STREAM.regionMatches(true, 0, contentType, 0, ContentType.TEXT_EVENT_STREAM.length()); } else { return false; } } /** * Processes the text event stream * * @param httpRequest The HTTP Request * @param httpRequestConsumer The HTTP Request consumer * @param inputStream The input stream * @param listener The listener object attached with the httpRequest * @param logger The logger object */ public static void processTextEventStream(HttpRequest httpRequest, Consumer<HttpRequest> httpRequestConsumer, InputStream inputStream, ServerSentEventListener listener, ClientLogger logger) { RetrySSEResult retrySSEResult; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { retrySSEResult = processBuffer(reader, listener); if (retrySSEResult != null && !retryExceptionForSSE(retrySSEResult, listener, httpRequest) && !Thread.currentThread().isInterrupted()) { httpRequestConsumer.accept(httpRequest); } } catch (IOException e) { throw logger.logThrowableAsError(new UncheckedIOException(e)); } } /** * Processes the sse buffer and dispatches the event * * @param reader The BufferedReader object * @param listener The listener object attached with the httpRequest */ private static RetrySSEResult processBuffer(BufferedReader reader, ServerSentEventListener listener) { StringBuilder collectedData = new StringBuilder(); ServerSentEvent event = null; try { String line; while ((line = reader.readLine()) != null) { collectedData.append(line).append("\n"); if (isEndOfBlock(collectedData)) { event = processLines(collectedData.toString().split("\n")); if (!Objects.equals(event.getEvent(), DEFAULT_EVENT) || event.getData() != null) { listener.onEvent(event); } collectedData = new StringBuilder(); } } listener.onClose(); } catch (IOException e) { return new RetrySSEResult(e, event != null ? event.getId() : -1, event != null ? ServerSentEventHelper.getRetryAfter(event) : null); } return null; } /** * Retries the request if the listener allows it * * @param retrySSEResult the result of the retry * @param listener The listener object attached with the httpRequest * @param httpRequest the HTTP Request being sent */ private static boolean retryExceptionForSSE(RetrySSEResult retrySSEResult, ServerSentEventListener listener, HttpRequest httpRequest) { if (Thread.currentThread().isInterrupted() || !listener.shouldRetry(retrySSEResult.getException(), retrySSEResult.getRetryAfter(), retrySSEResult.getLastEventId())) { listener.onError(retrySSEResult.getException()); return true; } if (retrySSEResult.getLastEventId() != -1) { httpRequest.getHeaders() .add(HttpHeaderName.fromString(LAST_EVENT_ID), String.valueOf(retrySSEResult.getLastEventId())); } try { if (retrySSEResult.getRetryAfter() != null) { Thread.sleep(retrySSEResult.getRetryAfter().toMillis()); } } catch (InterruptedException ignored) { return true; } return false; } private static ServerSentEvent processLines(String[] lines) { List<String> eventData = null; ServerSentEvent event = new ServerSentEvent(); for (String line : lines) { int idx = line.indexOf(':'); if (idx == 0) { ServerSentEventHelper.setComment(event, line.substring(1).trim()); continue; } String field = line.substring(0, idx < 0 ? lines.length : idx).trim().toLowerCase(); String value = idx < 0 ? "" : line.substring(idx + 1).trim(); switch (field) { case "event": ServerSentEventHelper.setEvent(event, value); break; case "data": if (eventData == null) { eventData = new ArrayList<>(); } eventData.add(value); break; case "id": if (!value.isEmpty()) { ServerSentEventHelper.setId(event, Long.parseLong(value)); } break; case "retry": if (!value.isEmpty() && DIGITS_ONLY.matcher(value).matches()) { ServerSentEventHelper.setRetryAfter(event, Duration.ofMillis(Long.parseLong(value))); } break; default: break; } } if (event.getEvent() == null) { ServerSentEventHelper.setEvent(event, DEFAULT_EVENT); } if (eventData != null) { ServerSentEventHelper.setData(event, eventData); } return event; } /** * Inner Class to hold the result for a retry of an SSE request */ private static class RetrySSEResult { private final long lastEventId; private final Duration retryAfter; private final IOException ioException; RetrySSEResult(IOException e, long lastEventId, Duration retryAfter) { this.ioException = e; this.lastEventId = lastEventId; this.retryAfter = retryAfter; } public long getLastEventId() { return lastEventId; } public Duration getRetryAfter() { return retryAfter; } public IOException getException() { return ioException; } } }
Doesn't the specification say to ignore in this case? Wouldn't this be incorrect behavior to throw?
private static ServerSentEvent processLines(String[] lines) { List<String> eventData = null; ServerSentEvent event = new ServerSentEvent(); for (String line : lines) { int idx = line.indexOf(':'); if (idx == 0) { ServerSentEventHelper.setComment(event, line.substring(1).trim()); continue; } String field = line.substring(0, idx < 0 ? lines.length : idx).trim().toLowerCase(); String value = idx < 0 ? "" : line.substring(idx + 1).trim(); switch (field) { case "event": ServerSentEventHelper.setEvent(event, value); break; case "data": if(eventData == null) { eventData = new ArrayList<>(); } eventData.add(value); break; case "id": if (!value.isEmpty()) { ServerSentEventHelper.setId(event, Long.parseLong(value)); } break; case "retry": if (!value.isEmpty() && DIGITS_ONLY.matcher(value).matches()) { ServerSentEventHelper.setRetryAfter(event, Duration.ofMillis(Long.parseLong(value))); } break; default: throw new IllegalArgumentException("Invalid data received from server"); } } if (event.getEvent() == null) { ServerSentEventHelper.setEvent(event, DEFAULT_EVENT); } if (eventData != null) { ServerSentEventHelper.setData(event, eventData); } return event; }
throw new IllegalArgumentException("Invalid data received from server");
private static ServerSentEvent processLines(String[] lines) { List<String> eventData = null; ServerSentEvent event = new ServerSentEvent(); for (String line : lines) { int idx = line.indexOf(':'); if (idx == 0) { ServerSentEventHelper.setComment(event, line.substring(1).trim()); continue; } String field = line.substring(0, idx < 0 ? lines.length : idx).trim().toLowerCase(); String value = idx < 0 ? "" : line.substring(idx + 1).trim(); switch (field) { case "event": ServerSentEventHelper.setEvent(event, value); break; case "data": if (eventData == null) { eventData = new ArrayList<>(); } eventData.add(value); break; case "id": if (!value.isEmpty()) { ServerSentEventHelper.setId(event, Long.parseLong(value)); } break; case "retry": if (!value.isEmpty() && DIGITS_ONLY.matcher(value).matches()) { ServerSentEventHelper.setRetryAfter(event, Duration.ofMillis(Long.parseLong(value))); } break; default: break; } } if (event.getEvent() == null) { ServerSentEventHelper.setEvent(event, DEFAULT_EVENT); } if (eventData != null) { ServerSentEventHelper.setData(event, eventData); } return event; }
class ServerSentEventUtil { private static final String DEFAULT_EVENT = "message"; private static final Pattern DIGITS_ONLY = Pattern.compile("^[\\d]*$"); private static final String LAST_EVENT_ID = "Last-Event-Id"; public static final String NO_LISTENER_LOG_MESSAGE = "No listener attached to the server sent event http request." + " Treating response as regular response."; private static boolean isEndOfBlock(StringBuilder sb) { return sb.indexOf("\n\n") >= 0; } /** * Processes the sse buffer and dispatches the event * * @param reader The BufferedReader object * @param listener The listener object attached with the httpRequest */ public static RetrySSEResult processBuffer(BufferedReader reader, ServerSentEventListener listener) { StringBuilder collectedData = new StringBuilder(); ServerSentEvent event = null; try { String line; while ((line = reader.readLine()) != null) { collectedData.append(line).append("\n"); if (isEndOfBlock(collectedData)) { event = processLines(collectedData.toString().split("\n")); if (!Objects.equals(event.getEvent(), DEFAULT_EVENT) || event.getData() != null) { listener.onEvent(event); } collectedData = new StringBuilder(); } } listener.onClose(); } catch (IOException e) { return new RetrySSEResult(e, event != null ? event.getId() : -1, event != null ? ServerSentEventHelper.getRetryAfter(event) : null); } return null; } /** * Retries the request if the listener allows it * * @param retrySSEResult the result of the retry * @param listener The listener object attached with the httpRequest * @param httpRequest the HTTP Request being sent */ public static boolean retryExceptionForSSE(RetrySSEResult retrySSEResult, ServerSentEventListener listener, HttpRequest httpRequest) { if (Thread.currentThread().isInterrupted() || !listener.shouldRetry(retrySSEResult.getException(), retrySSEResult.getRetryAfter(), retrySSEResult.getLastEventId())) { listener.onError(retrySSEResult.getException()); return true; } if (retrySSEResult.getLastEventId() != -1) { httpRequest.getHeaders() .add(HeaderName.fromString(LAST_EVENT_ID), String.valueOf(retrySSEResult.getLastEventId())); } try { if (retrySSEResult.getRetryAfter() != null) { Thread.sleep(retrySSEResult.getRetryAfter().toMillis()); } } catch (InterruptedException ignored) { return true; } return false; } }
class ServerSentEventUtil { private static final String DEFAULT_EVENT = "message"; private static final Pattern DIGITS_ONLY = Pattern.compile("^[\\d]*$"); private static final String LAST_EVENT_ID = "Last-Event-Id"; public static final String NO_LISTENER_ERROR_MESSAGE = "No ServerSentEventListener attached to HttpRequest to " + "handle the text/event-stream response"; private ServerSentEventUtil() { } /** * Checks if the content type is a text event stream * * @param contentType The content type * @return True if the content type is a text event stream */ public static boolean isTextEventStreamContentType(String contentType) { if (contentType != null) { return ContentType.TEXT_EVENT_STREAM.regionMatches(true, 0, contentType, 0, ContentType.TEXT_EVENT_STREAM.length()); } else { return false; } } /** * Processes the text event stream * * @param httpRequest The HTTP Request * @param httpRequestConsumer The HTTP Request consumer * @param inputStream The input stream * @param listener The listener object attached with the httpRequest * @param logger The logger object */ public static void processTextEventStream(HttpRequest httpRequest, Consumer<HttpRequest> httpRequestConsumer, InputStream inputStream, ServerSentEventListener listener, ClientLogger logger) { RetrySSEResult retrySSEResult; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { retrySSEResult = processBuffer(reader, listener); if (retrySSEResult != null && !retryExceptionForSSE(retrySSEResult, listener, httpRequest) && !Thread.currentThread().isInterrupted()) { httpRequestConsumer.accept(httpRequest); } } catch (IOException e) { throw logger.logThrowableAsError(new UncheckedIOException(e)); } } private static boolean isEndOfBlock(StringBuilder sb) { return sb.lastIndexOf("\n\n") >= 0; } /** * Processes the sse buffer and dispatches the event * * @param reader The BufferedReader object * @param listener The listener object attached with the httpRequest */ private static RetrySSEResult processBuffer(BufferedReader reader, ServerSentEventListener listener) { StringBuilder collectedData = new StringBuilder(); ServerSentEvent event = null; try { String line; while ((line = reader.readLine()) != null) { collectedData.append(line).append("\n"); if (isEndOfBlock(collectedData)) { event = processLines(collectedData.toString().split("\n")); if (!Objects.equals(event.getEvent(), DEFAULT_EVENT) || event.getData() != null) { listener.onEvent(event); } collectedData = new StringBuilder(); } } listener.onClose(); } catch (IOException e) { return new RetrySSEResult(e, event != null ? event.getId() : -1, event != null ? ServerSentEventHelper.getRetryAfter(event) : null); } return null; } /** * Retries the request if the listener allows it * * @param retrySSEResult the result of the retry * @param listener The listener object attached with the httpRequest * @param httpRequest the HTTP Request being sent */ private static boolean retryExceptionForSSE(RetrySSEResult retrySSEResult, ServerSentEventListener listener, HttpRequest httpRequest) { if (Thread.currentThread().isInterrupted() || !listener.shouldRetry(retrySSEResult.getException(), retrySSEResult.getRetryAfter(), retrySSEResult.getLastEventId())) { listener.onError(retrySSEResult.getException()); return true; } if (retrySSEResult.getLastEventId() != -1) { httpRequest.getHeaders() .add(HttpHeaderName.fromString(LAST_EVENT_ID), String.valueOf(retrySSEResult.getLastEventId())); } try { if (retrySSEResult.getRetryAfter() != null) { Thread.sleep(retrySSEResult.getRetryAfter().toMillis()); } } catch (InterruptedException ignored) { return true; } return false; } /** * Inner Class to hold the result for a retry of an SSE request */ private static class RetrySSEResult { private final long lastEventId; private final Duration retryAfter; private final IOException ioException; RetrySSEResult(IOException e, long lastEventId, Duration retryAfter) { this.ioException = e; this.lastEventId = lastEventId; this.retryAfter = retryAfter; } public long getLastEventId() { return lastEventId; } public Duration getRetryAfter() { return retryAfter; } public IOException getException() { return ioException; } } }
We should add in proper handling for `Content-Type` here and update `ContentType` to perform this action.
private static boolean isTextEventStream(okhttp3.Headers responseHeaders) { return responseHeaders != null && responseHeaders.get(HeaderName.CONTENT_TYPE.toString()) != null && Objects.equals(responseHeaders.get(HeaderName.CONTENT_TYPE.toString()), ContentType.TEXT_EVENT_STREAM); }
Objects.equals(responseHeaders.get(HeaderName.CONTENT_TYPE.toString()), ContentType.TEXT_EVENT_STREAM);
private static boolean isTextEventStream(okhttp3.Headers responseHeaders) { if (responseHeaders != null) { return ServerSentEventUtil .isTextEventStreamContentType(responseHeaders.get(HttpHeaderName.CONTENT_TYPE.toString())); } return false; }
class OkHttpHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); final OkHttpClient httpClient; OkHttpHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Response<?> send(HttpRequest request) { boolean eagerlyConvertHeaders = request.getMetadata().isEagerlyConvertHeaders(); boolean eagerlyReadResponse = request.getMetadata().isEagerlyReadResponse(); boolean ignoreResponseBody = request.getMetadata().isIgnoreResponseBody(); Request okHttpRequest = toOkHttpRequest(request); try { okhttp3.Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } /** * Converts the given generic-core request to okhttp request. * * @param request the generic-core request. * * @return Th eOkHttp request. */ private okhttp3.Request toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (Header hdr : request.getHeaders()) { hdr.getValues().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBody(), request.getHeaders()); return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody).build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * * @return The Mono emitting okhttp request */ private RequestBody toOkHttpRequestBody(BinaryData bodyContent, Headers headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); if (bodyContent instanceof InputStreamBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpInputStreamRequestBody((InputStreamBinaryData) bodyContent, effectiveContentLength, mediaType); } else if (bodyContent instanceof FileBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpFileRequestBody((FileBinaryData) bodyContent, effectiveContentLength, mediaType); } else { return RequestBody.create(bodyContent.toBytes(), mediaType); } } private static long getRequestContentLength(BinaryData content, Headers headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private Response<?> toResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { okhttp3.Headers responseHeaders = response.headers(); if (isTextEventStream(responseHeaders)) { return processServerSentEvent(request, response, eagerlyConvertHeaders); } else { return processResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } } private OkHttpResponse processServerSentEvent(HttpRequest request, okhttp3.Response response, boolean eagerlyConvertHeaders) { ServerSentEventListener listener = request.getServerSentEventListener(); if (listener != null && response.body() != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8))) { RetrySSEResult retrySSEResult = processBuffer(reader, listener); if (retrySSEResult != null && !retryExceptionForSSE(retrySSEResult, listener, request) && !Thread.currentThread().isInterrupted()) { this.send(request); } } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } else { LOGGER.atInfo().log(() -> NO_LISTENER_LOG_MESSAGE); } return new OkHttpResponse(response, request, eagerlyConvertHeaders, EMPTY_BODY); } private Response<?> processResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpResponse(response, request, eagerlyConvertHeaders, bytes); } } else { return new OkHttpResponse(response, request, eagerlyConvertHeaders, null); } } }
class OkHttpHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); final OkHttpClient httpClient; OkHttpHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Response<?> send(HttpRequest request) { boolean eagerlyConvertHeaders = request.getMetadata().isEagerlyConvertHeaders(); boolean eagerlyReadResponse = request.getMetadata().isEagerlyReadResponse(); boolean ignoreResponseBody = request.getMetadata().isIgnoreResponseBody(); Request okHttpRequest = toOkHttpRequest(request); try { okhttp3.Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } /** * Converts the given generic-core request to okhttp request. * * @param request the generic-core request. * * @return Th eOkHttp request. */ private okhttp3.Request toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValues().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBody(), request.getHeaders()); return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody).build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * * @return The Mono emitting okhttp request */ private RequestBody toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HttpHeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); if (bodyContent instanceof InputStreamBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpInputStreamRequestBody((InputStreamBinaryData) bodyContent, effectiveContentLength, mediaType); } else if (bodyContent instanceof FileBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpFileRequestBody((FileBinaryData) bodyContent, effectiveContentLength, mediaType); } else { return RequestBody.create(bodyContent.toBytes(), mediaType); } } private static long getRequestContentLength(BinaryData content, HttpHeaders headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HttpHeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private Response<?> toResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { okhttp3.Headers responseHeaders = response.headers(); if (isTextEventStream(responseHeaders) && response.body() != null) { ServerSentEventListener listener = request.getServerSentEventListener(); if (listener != null) { processTextEventStream(request, httpRequest -> this.send(httpRequest), response.body().byteStream(), listener, LOGGER); } else { throw LOGGER.logThrowableAsError(new RuntimeException(ServerSentEventUtil.NO_LISTENER_ERROR_MESSAGE)); } return new OkHttpResponse(response, request, eagerlyConvertHeaders, EMPTY_BODY); } return processResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } private Response<?> processResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpResponse(response, request, eagerlyConvertHeaders, bytes); } } else { return new OkHttpResponse(response, request, eagerlyConvertHeaders, null); } } }
I think @srnagar and we had some back and forth discussion on this. https://github.com/Azure/azure-sdk-for-java/pull/38349#discussion_r1470339921 We decided to error out on receiving invalid pattern as that could result in huge streams of unwanted data. Ref from previous PR - https://github.com/Azure/azure-sdk-for-java/pull/38349#discussion_r1483714394
private static ServerSentEvent processLines(String[] lines) { List<String> eventData = null; ServerSentEvent event = new ServerSentEvent(); for (String line : lines) { int idx = line.indexOf(':'); if (idx == 0) { ServerSentEventHelper.setComment(event, line.substring(1).trim()); continue; } String field = line.substring(0, idx < 0 ? lines.length : idx).trim().toLowerCase(); String value = idx < 0 ? "" : line.substring(idx + 1).trim(); switch (field) { case "event": ServerSentEventHelper.setEvent(event, value); break; case "data": if(eventData == null) { eventData = new ArrayList<>(); } eventData.add(value); break; case "id": if (!value.isEmpty()) { ServerSentEventHelper.setId(event, Long.parseLong(value)); } break; case "retry": if (!value.isEmpty() && DIGITS_ONLY.matcher(value).matches()) { ServerSentEventHelper.setRetryAfter(event, Duration.ofMillis(Long.parseLong(value))); } break; default: throw new IllegalArgumentException("Invalid data received from server"); } } if (event.getEvent() == null) { ServerSentEventHelper.setEvent(event, DEFAULT_EVENT); } if (eventData != null) { ServerSentEventHelper.setData(event, eventData); } return event; }
throw new IllegalArgumentException("Invalid data received from server");
private static ServerSentEvent processLines(String[] lines) { List<String> eventData = null; ServerSentEvent event = new ServerSentEvent(); for (String line : lines) { int idx = line.indexOf(':'); if (idx == 0) { ServerSentEventHelper.setComment(event, line.substring(1).trim()); continue; } String field = line.substring(0, idx < 0 ? lines.length : idx).trim().toLowerCase(); String value = idx < 0 ? "" : line.substring(idx + 1).trim(); switch (field) { case "event": ServerSentEventHelper.setEvent(event, value); break; case "data": if (eventData == null) { eventData = new ArrayList<>(); } eventData.add(value); break; case "id": if (!value.isEmpty()) { ServerSentEventHelper.setId(event, Long.parseLong(value)); } break; case "retry": if (!value.isEmpty() && DIGITS_ONLY.matcher(value).matches()) { ServerSentEventHelper.setRetryAfter(event, Duration.ofMillis(Long.parseLong(value))); } break; default: break; } } if (event.getEvent() == null) { ServerSentEventHelper.setEvent(event, DEFAULT_EVENT); } if (eventData != null) { ServerSentEventHelper.setData(event, eventData); } return event; }
class ServerSentEventUtil { private static final String DEFAULT_EVENT = "message"; private static final Pattern DIGITS_ONLY = Pattern.compile("^[\\d]*$"); private static final String LAST_EVENT_ID = "Last-Event-Id"; public static final String NO_LISTENER_LOG_MESSAGE = "No listener attached to the server sent event http request." + " Treating response as regular response."; private static boolean isEndOfBlock(StringBuilder sb) { return sb.indexOf("\n\n") >= 0; } /** * Processes the sse buffer and dispatches the event * * @param reader The BufferedReader object * @param listener The listener object attached with the httpRequest */ public static RetrySSEResult processBuffer(BufferedReader reader, ServerSentEventListener listener) { StringBuilder collectedData = new StringBuilder(); ServerSentEvent event = null; try { String line; while ((line = reader.readLine()) != null) { collectedData.append(line).append("\n"); if (isEndOfBlock(collectedData)) { event = processLines(collectedData.toString().split("\n")); if (!Objects.equals(event.getEvent(), DEFAULT_EVENT) || event.getData() != null) { listener.onEvent(event); } collectedData = new StringBuilder(); } } listener.onClose(); } catch (IOException e) { return new RetrySSEResult(e, event != null ? event.getId() : -1, event != null ? ServerSentEventHelper.getRetryAfter(event) : null); } return null; } /** * Retries the request if the listener allows it * * @param retrySSEResult the result of the retry * @param listener The listener object attached with the httpRequest * @param httpRequest the HTTP Request being sent */ public static boolean retryExceptionForSSE(RetrySSEResult retrySSEResult, ServerSentEventListener listener, HttpRequest httpRequest) { if (Thread.currentThread().isInterrupted() || !listener.shouldRetry(retrySSEResult.getException(), retrySSEResult.getRetryAfter(), retrySSEResult.getLastEventId())) { listener.onError(retrySSEResult.getException()); return true; } if (retrySSEResult.getLastEventId() != -1) { httpRequest.getHeaders() .add(HeaderName.fromString(LAST_EVENT_ID), String.valueOf(retrySSEResult.getLastEventId())); } try { if (retrySSEResult.getRetryAfter() != null) { Thread.sleep(retrySSEResult.getRetryAfter().toMillis()); } } catch (InterruptedException ignored) { return true; } return false; } }
class ServerSentEventUtil { private static final String DEFAULT_EVENT = "message"; private static final Pattern DIGITS_ONLY = Pattern.compile("^[\\d]*$"); private static final String LAST_EVENT_ID = "Last-Event-Id"; public static final String NO_LISTENER_ERROR_MESSAGE = "No ServerSentEventListener attached to HttpRequest to " + "handle the text/event-stream response"; private ServerSentEventUtil() { } /** * Checks if the content type is a text event stream * * @param contentType The content type * @return True if the content type is a text event stream */ public static boolean isTextEventStreamContentType(String contentType) { if (contentType != null) { return ContentType.TEXT_EVENT_STREAM.regionMatches(true, 0, contentType, 0, ContentType.TEXT_EVENT_STREAM.length()); } else { return false; } } /** * Processes the text event stream * * @param httpRequest The HTTP Request * @param httpRequestConsumer The HTTP Request consumer * @param inputStream The input stream * @param listener The listener object attached with the httpRequest * @param logger The logger object */ public static void processTextEventStream(HttpRequest httpRequest, Consumer<HttpRequest> httpRequestConsumer, InputStream inputStream, ServerSentEventListener listener, ClientLogger logger) { RetrySSEResult retrySSEResult; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { retrySSEResult = processBuffer(reader, listener); if (retrySSEResult != null && !retryExceptionForSSE(retrySSEResult, listener, httpRequest) && !Thread.currentThread().isInterrupted()) { httpRequestConsumer.accept(httpRequest); } } catch (IOException e) { throw logger.logThrowableAsError(new UncheckedIOException(e)); } } private static boolean isEndOfBlock(StringBuilder sb) { return sb.lastIndexOf("\n\n") >= 0; } /** * Processes the sse buffer and dispatches the event * * @param reader The BufferedReader object * @param listener The listener object attached with the httpRequest */ private static RetrySSEResult processBuffer(BufferedReader reader, ServerSentEventListener listener) { StringBuilder collectedData = new StringBuilder(); ServerSentEvent event = null; try { String line; while ((line = reader.readLine()) != null) { collectedData.append(line).append("\n"); if (isEndOfBlock(collectedData)) { event = processLines(collectedData.toString().split("\n")); if (!Objects.equals(event.getEvent(), DEFAULT_EVENT) || event.getData() != null) { listener.onEvent(event); } collectedData = new StringBuilder(); } } listener.onClose(); } catch (IOException e) { return new RetrySSEResult(e, event != null ? event.getId() : -1, event != null ? ServerSentEventHelper.getRetryAfter(event) : null); } return null; } /** * Retries the request if the listener allows it * * @param retrySSEResult the result of the retry * @param listener The listener object attached with the httpRequest * @param httpRequest the HTTP Request being sent */ private static boolean retryExceptionForSSE(RetrySSEResult retrySSEResult, ServerSentEventListener listener, HttpRequest httpRequest) { if (Thread.currentThread().isInterrupted() || !listener.shouldRetry(retrySSEResult.getException(), retrySSEResult.getRetryAfter(), retrySSEResult.getLastEventId())) { listener.onError(retrySSEResult.getException()); return true; } if (retrySSEResult.getLastEventId() != -1) { httpRequest.getHeaders() .add(HttpHeaderName.fromString(LAST_EVENT_ID), String.valueOf(retrySSEResult.getLastEventId())); } try { if (retrySSEResult.getRetryAfter() != null) { Thread.sleep(retrySSEResult.getRetryAfter().toMillis()); } } catch (InterruptedException ignored) { return true; } return false; } /** * Inner Class to hold the result for a retry of an SSE request */ private static class RetrySSEResult { private final long lastEventId; private final Duration retryAfter; private final IOException ioException; RetrySSEResult(IOException e, long lastEventId, Duration retryAfter) { this.ioException = e; this.lastEventId = lastEventId; this.retryAfter = retryAfter; } public long getLastEventId() { return lastEventId; } public Duration getRetryAfter() { return retryAfter; } public IOException getException() { return ioException; } } }
Closing on this: Let's stick to [specification ](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation) for now which suggests to ignore invalid data.
private static ServerSentEvent processLines(String[] lines) { List<String> eventData = null; ServerSentEvent event = new ServerSentEvent(); for (String line : lines) { int idx = line.indexOf(':'); if (idx == 0) { ServerSentEventHelper.setComment(event, line.substring(1).trim()); continue; } String field = line.substring(0, idx < 0 ? lines.length : idx).trim().toLowerCase(); String value = idx < 0 ? "" : line.substring(idx + 1).trim(); switch (field) { case "event": ServerSentEventHelper.setEvent(event, value); break; case "data": if(eventData == null) { eventData = new ArrayList<>(); } eventData.add(value); break; case "id": if (!value.isEmpty()) { ServerSentEventHelper.setId(event, Long.parseLong(value)); } break; case "retry": if (!value.isEmpty() && DIGITS_ONLY.matcher(value).matches()) { ServerSentEventHelper.setRetryAfter(event, Duration.ofMillis(Long.parseLong(value))); } break; default: throw new IllegalArgumentException("Invalid data received from server"); } } if (event.getEvent() == null) { ServerSentEventHelper.setEvent(event, DEFAULT_EVENT); } if (eventData != null) { ServerSentEventHelper.setData(event, eventData); } return event; }
throw new IllegalArgumentException("Invalid data received from server");
private static ServerSentEvent processLines(String[] lines) { List<String> eventData = null; ServerSentEvent event = new ServerSentEvent(); for (String line : lines) { int idx = line.indexOf(':'); if (idx == 0) { ServerSentEventHelper.setComment(event, line.substring(1).trim()); continue; } String field = line.substring(0, idx < 0 ? lines.length : idx).trim().toLowerCase(); String value = idx < 0 ? "" : line.substring(idx + 1).trim(); switch (field) { case "event": ServerSentEventHelper.setEvent(event, value); break; case "data": if (eventData == null) { eventData = new ArrayList<>(); } eventData.add(value); break; case "id": if (!value.isEmpty()) { ServerSentEventHelper.setId(event, Long.parseLong(value)); } break; case "retry": if (!value.isEmpty() && DIGITS_ONLY.matcher(value).matches()) { ServerSentEventHelper.setRetryAfter(event, Duration.ofMillis(Long.parseLong(value))); } break; default: break; } } if (event.getEvent() == null) { ServerSentEventHelper.setEvent(event, DEFAULT_EVENT); } if (eventData != null) { ServerSentEventHelper.setData(event, eventData); } return event; }
class ServerSentEventUtil { private static final String DEFAULT_EVENT = "message"; private static final Pattern DIGITS_ONLY = Pattern.compile("^[\\d]*$"); private static final String LAST_EVENT_ID = "Last-Event-Id"; public static final String NO_LISTENER_LOG_MESSAGE = "No listener attached to the server sent event http request." + " Treating response as regular response."; private static boolean isEndOfBlock(StringBuilder sb) { return sb.indexOf("\n\n") >= 0; } /** * Processes the sse buffer and dispatches the event * * @param reader The BufferedReader object * @param listener The listener object attached with the httpRequest */ public static RetrySSEResult processBuffer(BufferedReader reader, ServerSentEventListener listener) { StringBuilder collectedData = new StringBuilder(); ServerSentEvent event = null; try { String line; while ((line = reader.readLine()) != null) { collectedData.append(line).append("\n"); if (isEndOfBlock(collectedData)) { event = processLines(collectedData.toString().split("\n")); if (!Objects.equals(event.getEvent(), DEFAULT_EVENT) || event.getData() != null) { listener.onEvent(event); } collectedData = new StringBuilder(); } } listener.onClose(); } catch (IOException e) { return new RetrySSEResult(e, event != null ? event.getId() : -1, event != null ? ServerSentEventHelper.getRetryAfter(event) : null); } return null; } /** * Retries the request if the listener allows it * * @param retrySSEResult the result of the retry * @param listener The listener object attached with the httpRequest * @param httpRequest the HTTP Request being sent */ public static boolean retryExceptionForSSE(RetrySSEResult retrySSEResult, ServerSentEventListener listener, HttpRequest httpRequest) { if (Thread.currentThread().isInterrupted() || !listener.shouldRetry(retrySSEResult.getException(), retrySSEResult.getRetryAfter(), retrySSEResult.getLastEventId())) { listener.onError(retrySSEResult.getException()); return true; } if (retrySSEResult.getLastEventId() != -1) { httpRequest.getHeaders() .add(HeaderName.fromString(LAST_EVENT_ID), String.valueOf(retrySSEResult.getLastEventId())); } try { if (retrySSEResult.getRetryAfter() != null) { Thread.sleep(retrySSEResult.getRetryAfter().toMillis()); } } catch (InterruptedException ignored) { return true; } return false; } }
class ServerSentEventUtil { private static final String DEFAULT_EVENT = "message"; private static final Pattern DIGITS_ONLY = Pattern.compile("^[\\d]*$"); private static final String LAST_EVENT_ID = "Last-Event-Id"; public static final String NO_LISTENER_ERROR_MESSAGE = "No ServerSentEventListener attached to HttpRequest to " + "handle the text/event-stream response"; private ServerSentEventUtil() { } /** * Checks if the content type is a text event stream * * @param contentType The content type * @return True if the content type is a text event stream */ public static boolean isTextEventStreamContentType(String contentType) { if (contentType != null) { return ContentType.TEXT_EVENT_STREAM.regionMatches(true, 0, contentType, 0, ContentType.TEXT_EVENT_STREAM.length()); } else { return false; } } /** * Processes the text event stream * * @param httpRequest The HTTP Request * @param httpRequestConsumer The HTTP Request consumer * @param inputStream The input stream * @param listener The listener object attached with the httpRequest * @param logger The logger object */ public static void processTextEventStream(HttpRequest httpRequest, Consumer<HttpRequest> httpRequestConsumer, InputStream inputStream, ServerSentEventListener listener, ClientLogger logger) { RetrySSEResult retrySSEResult; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { retrySSEResult = processBuffer(reader, listener); if (retrySSEResult != null && !retryExceptionForSSE(retrySSEResult, listener, httpRequest) && !Thread.currentThread().isInterrupted()) { httpRequestConsumer.accept(httpRequest); } } catch (IOException e) { throw logger.logThrowableAsError(new UncheckedIOException(e)); } } private static boolean isEndOfBlock(StringBuilder sb) { return sb.lastIndexOf("\n\n") >= 0; } /** * Processes the sse buffer and dispatches the event * * @param reader The BufferedReader object * @param listener The listener object attached with the httpRequest */ private static RetrySSEResult processBuffer(BufferedReader reader, ServerSentEventListener listener) { StringBuilder collectedData = new StringBuilder(); ServerSentEvent event = null; try { String line; while ((line = reader.readLine()) != null) { collectedData.append(line).append("\n"); if (isEndOfBlock(collectedData)) { event = processLines(collectedData.toString().split("\n")); if (!Objects.equals(event.getEvent(), DEFAULT_EVENT) || event.getData() != null) { listener.onEvent(event); } collectedData = new StringBuilder(); } } listener.onClose(); } catch (IOException e) { return new RetrySSEResult(e, event != null ? event.getId() : -1, event != null ? ServerSentEventHelper.getRetryAfter(event) : null); } return null; } /** * Retries the request if the listener allows it * * @param retrySSEResult the result of the retry * @param listener The listener object attached with the httpRequest * @param httpRequest the HTTP Request being sent */ private static boolean retryExceptionForSSE(RetrySSEResult retrySSEResult, ServerSentEventListener listener, HttpRequest httpRequest) { if (Thread.currentThread().isInterrupted() || !listener.shouldRetry(retrySSEResult.getException(), retrySSEResult.getRetryAfter(), retrySSEResult.getLastEventId())) { listener.onError(retrySSEResult.getException()); return true; } if (retrySSEResult.getLastEventId() != -1) { httpRequest.getHeaders() .add(HttpHeaderName.fromString(LAST_EVENT_ID), String.valueOf(retrySSEResult.getLastEventId())); } try { if (retrySSEResult.getRetryAfter() != null) { Thread.sleep(retrySSEResult.getRetryAfter().toMillis()); } } catch (InterruptedException ignored) { return true; } return false; } /** * Inner Class to hold the result for a retry of an SSE request */ private static class RetrySSEResult { private final long lastEventId; private final Duration retryAfter; private final IOException ioException; RetrySSEResult(IOException e, long lastEventId, Duration retryAfter) { this.ioException = e; this.lastEventId = lastEventId; this.retryAfter = retryAfter; } public long getLastEventId() { return lastEventId; } public Duration getRetryAfter() { return retryAfter; } public IOException getException() { return ioException; } } }
`equals` check will not work for all scenarios as services can send the content type as `text/event-stream; charset=utf8` which should still be treated as SSE. So, we should use `startsWith` instead of `equals`.
private static boolean isTextEventStream(okhttp3.Headers responseHeaders) { return responseHeaders != null && ContentType.TEXT_EVENT_STREAM.equals(responseHeaders.get(HeaderName.CONTENT_TYPE.toString())); }
&& ContentType.TEXT_EVENT_STREAM.equals(responseHeaders.get(HeaderName.CONTENT_TYPE.toString()));
private static boolean isTextEventStream(okhttp3.Headers responseHeaders) { if (responseHeaders != null) { return ServerSentEventUtil .isTextEventStreamContentType(responseHeaders.get(HttpHeaderName.CONTENT_TYPE.toString())); } return false; }
class OkHttpHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); final OkHttpClient httpClient; OkHttpHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Response<?> send(HttpRequest request) { boolean eagerlyConvertHeaders = request.getMetadata().isEagerlyConvertHeaders(); boolean eagerlyReadResponse = request.getMetadata().isEagerlyReadResponse(); boolean ignoreResponseBody = request.getMetadata().isIgnoreResponseBody(); Request okHttpRequest = toOkHttpRequest(request); try { okhttp3.Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } /** * Converts the given generic-core request to okhttp request. * * @param request the generic-core request. * * @return Th eOkHttp request. */ private okhttp3.Request toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (Header hdr : request.getHeaders()) { hdr.getValues().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBody(), request.getHeaders()); return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody).build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * * @return The Mono emitting okhttp request */ private RequestBody toOkHttpRequestBody(BinaryData bodyContent, Headers headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); if (bodyContent instanceof InputStreamBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpInputStreamRequestBody((InputStreamBinaryData) bodyContent, effectiveContentLength, mediaType); } else if (bodyContent instanceof FileBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpFileRequestBody((FileBinaryData) bodyContent, effectiveContentLength, mediaType); } else { return RequestBody.create(bodyContent.toBytes(), mediaType); } } private static long getRequestContentLength(BinaryData content, Headers headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private Response<?> toResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { okhttp3.Headers responseHeaders = response.headers(); if (isTextEventStream(responseHeaders) && response.body() != null) { ServerSentEventListener listener = request.getServerSentEventListener(); if (listener != null) { processTextEventStream(request, httpRequestConsumer -> this.send(request), response.body().byteStream(), listener, LOGGER); } else { throw LOGGER.logThrowableAsError(new RuntimeException("No listener attached to the request.")); } return new OkHttpResponse(response, request, eagerlyConvertHeaders, EMPTY_BODY); } return processResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } private Response<?> processResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpResponse(response, request, eagerlyConvertHeaders, bytes); } } else { return new OkHttpResponse(response, request, eagerlyConvertHeaders, null); } } }
class OkHttpHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); final OkHttpClient httpClient; OkHttpHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Response<?> send(HttpRequest request) { boolean eagerlyConvertHeaders = request.getMetadata().isEagerlyConvertHeaders(); boolean eagerlyReadResponse = request.getMetadata().isEagerlyReadResponse(); boolean ignoreResponseBody = request.getMetadata().isIgnoreResponseBody(); Request okHttpRequest = toOkHttpRequest(request); try { okhttp3.Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } /** * Converts the given generic-core request to okhttp request. * * @param request the generic-core request. * * @return Th eOkHttp request. */ private okhttp3.Request toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValues().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBody(), request.getHeaders()); return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody).build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * * @return The Mono emitting okhttp request */ private RequestBody toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HttpHeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); if (bodyContent instanceof InputStreamBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpInputStreamRequestBody((InputStreamBinaryData) bodyContent, effectiveContentLength, mediaType); } else if (bodyContent instanceof FileBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpFileRequestBody((FileBinaryData) bodyContent, effectiveContentLength, mediaType); } else { return RequestBody.create(bodyContent.toBytes(), mediaType); } } private static long getRequestContentLength(BinaryData content, HttpHeaders headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HttpHeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private Response<?> toResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { okhttp3.Headers responseHeaders = response.headers(); if (isTextEventStream(responseHeaders) && response.body() != null) { ServerSentEventListener listener = request.getServerSentEventListener(); if (listener != null) { processTextEventStream(request, httpRequest -> this.send(httpRequest), response.body().byteStream(), listener, LOGGER); } else { throw LOGGER.logThrowableAsError(new RuntimeException(ServerSentEventUtil.NO_LISTENER_ERROR_MESSAGE)); } return new OkHttpResponse(response, request, eagerlyConvertHeaders, EMPTY_BODY); } return processResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } private Response<?> processResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpResponse(response, request, eagerlyConvertHeaders, bytes); } } else { return new OkHttpResponse(response, request, eagerlyConvertHeaders, null); } } }
I think in all spots we're checking for the content type we should use ```java ContentType.TEXT_EVENT_STREAM.regionMatches(true, 0, responseHeaders.get(HeaderName.CONTENT_TYPE.toString()), 0, ContentType.TEXT_EVENT_STREAM.size()) ``` This will perform a case-insensitive comparison without instantiating a new string.
private static boolean isTextEventStream(okhttp3.Headers responseHeaders) { return responseHeaders != null && ContentType.TEXT_EVENT_STREAM.equals(responseHeaders.get(HeaderName.CONTENT_TYPE.toString())); }
&& ContentType.TEXT_EVENT_STREAM.equals(responseHeaders.get(HeaderName.CONTENT_TYPE.toString()));
private static boolean isTextEventStream(okhttp3.Headers responseHeaders) { if (responseHeaders != null) { return ServerSentEventUtil .isTextEventStreamContentType(responseHeaders.get(HttpHeaderName.CONTENT_TYPE.toString())); } return false; }
class OkHttpHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); final OkHttpClient httpClient; OkHttpHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Response<?> send(HttpRequest request) { boolean eagerlyConvertHeaders = request.getMetadata().isEagerlyConvertHeaders(); boolean eagerlyReadResponse = request.getMetadata().isEagerlyReadResponse(); boolean ignoreResponseBody = request.getMetadata().isIgnoreResponseBody(); Request okHttpRequest = toOkHttpRequest(request); try { okhttp3.Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } /** * Converts the given generic-core request to okhttp request. * * @param request the generic-core request. * * @return Th eOkHttp request. */ private okhttp3.Request toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (Header hdr : request.getHeaders()) { hdr.getValues().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBody(), request.getHeaders()); return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody).build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * * @return The Mono emitting okhttp request */ private RequestBody toOkHttpRequestBody(BinaryData bodyContent, Headers headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); if (bodyContent instanceof InputStreamBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpInputStreamRequestBody((InputStreamBinaryData) bodyContent, effectiveContentLength, mediaType); } else if (bodyContent instanceof FileBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpFileRequestBody((FileBinaryData) bodyContent, effectiveContentLength, mediaType); } else { return RequestBody.create(bodyContent.toBytes(), mediaType); } } private static long getRequestContentLength(BinaryData content, Headers headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private Response<?> toResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { okhttp3.Headers responseHeaders = response.headers(); if (isTextEventStream(responseHeaders) && response.body() != null) { ServerSentEventListener listener = request.getServerSentEventListener(); if (listener != null) { processTextEventStream(request, httpRequestConsumer -> this.send(request), response.body().byteStream(), listener, LOGGER); } else { throw LOGGER.logThrowableAsError(new RuntimeException("No listener attached to the request.")); } return new OkHttpResponse(response, request, eagerlyConvertHeaders, EMPTY_BODY); } return processResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } private Response<?> processResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpResponse(response, request, eagerlyConvertHeaders, bytes); } } else { return new OkHttpResponse(response, request, eagerlyConvertHeaders, null); } } }
class OkHttpHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); final OkHttpClient httpClient; OkHttpHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Response<?> send(HttpRequest request) { boolean eagerlyConvertHeaders = request.getMetadata().isEagerlyConvertHeaders(); boolean eagerlyReadResponse = request.getMetadata().isEagerlyReadResponse(); boolean ignoreResponseBody = request.getMetadata().isIgnoreResponseBody(); Request okHttpRequest = toOkHttpRequest(request); try { okhttp3.Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } /** * Converts the given generic-core request to okhttp request. * * @param request the generic-core request. * * @return Th eOkHttp request. */ private okhttp3.Request toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValues().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBody(), request.getHeaders()); return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody).build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * * @return The Mono emitting okhttp request */ private RequestBody toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HttpHeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); if (bodyContent instanceof InputStreamBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpInputStreamRequestBody((InputStreamBinaryData) bodyContent, effectiveContentLength, mediaType); } else if (bodyContent instanceof FileBinaryData) { long effectiveContentLength = getRequestContentLength(bodyContent, headers); return new OkHttpFileRequestBody((FileBinaryData) bodyContent, effectiveContentLength, mediaType); } else { return RequestBody.create(bodyContent.toBytes(), mediaType); } } private static long getRequestContentLength(BinaryData content, HttpHeaders headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HttpHeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private Response<?> toResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { okhttp3.Headers responseHeaders = response.headers(); if (isTextEventStream(responseHeaders) && response.body() != null) { ServerSentEventListener listener = request.getServerSentEventListener(); if (listener != null) { processTextEventStream(request, httpRequest -> this.send(httpRequest), response.body().byteStream(), listener, LOGGER); } else { throw LOGGER.logThrowableAsError(new RuntimeException(ServerSentEventUtil.NO_LISTENER_ERROR_MESSAGE)); } return new OkHttpResponse(response, request, eagerlyConvertHeaders, EMPTY_BODY); } return processResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } private Response<?> processResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpResponse(response, request, eagerlyConvertHeaders, bytes); } } else { return new OkHttpResponse(response, request, eagerlyConvertHeaders, null); } } }
Please, add a test with no prompt.
public void holdWithResponseTest() { callMedia = getMockCallMedia(200); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id"), new TextSource().setText("audio to play")); StepVerifier.create( callMedia.holdWithResponse(options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); }
new TextSource().setText("audio to play"));
public void holdWithResponseTest() { callMedia = getMockCallMedia(200); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id")) .setPlaySourceInfo(new TextSource().setText("audio to play")); StepVerifier.create( callMedia.holdWithResponse(options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); }
class CallMediaAsyncUnitTests { private CallMediaAsync callMedia; private FileSource playFileSource; private TextSource playTextSource; private SsmlSource playSsmlSource; private PlayOptions playOptions; private PlayToAllOptions playToAllOptions; @BeforeEach public void setup() { callMedia = getMockCallMedia(202); playFileSource = new FileSource(); playFileSource.setPlaySourceCacheId("playFileSourceId"); playFileSource.setUrl("filePath"); playTextSource = new TextSource(); playTextSource.setPlaySourceCacheId("playTextSourceId"); playTextSource.setVoiceKind(VoiceKind.MALE); playTextSource.setSourceLocale("en-US"); playTextSource.setVoiceName("LULU"); playTextSource.setCustomVoiceEndpointId("customVoiceEndpointId"); playSsmlSource = new SsmlSource(); playSsmlSource.setSsmlText("<speak><voice name=\"LULU\"></voice></speak>"); playSsmlSource.setCustomVoiceEndpointId("customVoiceEndpointId"); } @Test public void playFileWithResponseTest() { playOptions = new PlayOptions(playFileSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playFileToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playFileToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextWithResponseTest() { playOptions = new PlayOptions(playTextSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlWithResponseTest() { playOptions = new PlayOptions(playSsmlSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playSsmlSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playSsmlSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void cancelAllOperationsWithResponse() { StepVerifier.create( callMedia.cancelAllMediaOperationsWithResponse()) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponse() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 1); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseWithFileSourceDtmfOptions() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); recognizeOptions.setInterToneTimeout(Duration.ofSeconds(3)); List<DtmfTone> stopDtmfTones = new ArrayList<>(); stopDtmfTones.add(DtmfTone.ZERO); stopDtmfTones.add(DtmfTone.ONE); stopDtmfTones.add(DtmfTone.TWO); recognizeOptions.setStopTones(stopDtmfTones); recognizeOptions.setRecognizeInputType(RecognizeInputType.DTMF); recognizeOptions.setPlayPrompt(new FileSource().setUrl("abc")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void startContinuousDtmfRecognitionWithResponse() { callMedia = getMockCallMedia(200); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); StepVerifier.create( callMedia.startContinuousDtmfRecognitionWithResponse( options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void stopContinuousDtmfRecognitionWithResponse() { callMedia = getMockCallMedia(200); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); StepVerifier.create( callMedia.stopContinuousDtmfRecognitionWithResponse( options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void sendDtmfWithResponse() { CallConnectionAsync callConnection = CallAutomationUnitTestBase.getCallConnectionAsync(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext("operationContext")), 202))) ); callMedia = callConnection.getCallMediaAsync(); List<DtmfTone> tones = Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()); SendDtmfTonesOptions options = new SendDtmfTonesOptions(tones, new CommunicationUserIdentifier("id")); options.setOperationContext("operationContext"); options.setOperationCallbackUrl(CallAutomationUnitTestBase.CALL_CALLBACK_URL); StepVerifier.create(callMedia.sendDtmfTonesWithResponse(options)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())).verifyComplete(); } @Test public void recognizeWithResponseWithTextSourceDtmfOptions() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); recognizeOptions.setInterToneTimeout(Duration.ofSeconds(3)); List<DtmfTone> stopDtmfTones = new ArrayList<>(); stopDtmfTones.add(DtmfTone.ZERO); stopDtmfTones.add(DtmfTone.ONE); stopDtmfTones.add(DtmfTone.TWO); recognizeOptions.setRecognizeInputType(RecognizeInputType.DTMF); recognizeOptions.setStopTones(stopDtmfTones); recognizeOptions.setPlayPrompt(new TextSource().setText("Test dmtf option with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseWithFileSourceChoiceOptions() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); recognizeChoice1.setTone(DtmfTone.ZERO); recognizeChoice2.setTone(DtmfTone.SIX); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions recognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); recognizeOptions.setRecognizeInputType(RecognizeInputType.CHOICES); recognizeOptions.setPlayPrompt(new FileSource().setUrl("abc")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechLanguage("en-US"); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextChoiceOptions() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); recognizeChoice1.setTone(DtmfTone.ZERO); recognizeChoice2.setTone(DtmfTone.THREE); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions recognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); recognizeOptions.setRecognizeInputType(RecognizeInputType.CHOICES); recognizeOptions.setPlayPrompt(new TextSource().setText("Test recognize choice with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechLanguage("en-US"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextSpeechOptions() { CallMediaRecognizeSpeechOptions recognizeOptions = new CallMediaRecognizeSpeechOptions(new CommunicationUserIdentifier("id"), Duration.ofMillis(1000)); recognizeOptions.setRecognizeInputType(RecognizeInputType.SPEECH); recognizeOptions.setPlayPrompt(new TextSource().setText("Test recognize speech or dtmf with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextSpeechOrDtmfOptions() { CallMediaRecognizeSpeechOrDtmfOptions recognizeOptions = new CallMediaRecognizeSpeechOrDtmfOptions(new CommunicationUserIdentifier("id"), 6, Duration.ofMillis(1000)); recognizeOptions.setRecognizeInputType(RecognizeInputType.SPEECH_OR_DTMF); recognizeOptions.setPlayPrompt(new SsmlSource().setSsmlText("<speak version=\"1.0\" xmlns=\"http: recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } private CallMediaAsync getMockCallMedia(int expectedStatusCode) { CallConnectionAsync callConnection = CallAutomationUnitTestBase.getCallConnectionAsync(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", expectedStatusCode))) ); return callConnection.getCallMediaAsync(); } @Test @Test public void unholdWithResponseTest() { callMedia = getMockCallMedia(200); StepVerifier.create( callMedia.unholdWithResponse( new CommunicationUserIdentifier("id"), "operationalContext" )) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void startTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StartTranscriptionOptions options = new StartTranscriptionOptions(); options.setOperationContext("operationContext"); options.setLocale("en-US"); StepVerifier.create( callMedia.startTranscriptionWithResponseAsync(options)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode()) ) .verifyComplete(); } @Test public void stopTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StopTranscriptionOptions options = new StopTranscriptionOptions(); options.setOperationContext("operationContext"); StepVerifier.create( callMedia.stopTranscriptionWithResponseAsync(options) ) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void updateTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StepVerifier.create( callMedia.updateTranscription("en-US") ).verifyComplete(); } }
class CallMediaAsyncUnitTests { private CallMediaAsync callMedia; private FileSource playFileSource; private TextSource playTextSource; private SsmlSource playSsmlSource; private PlayOptions playOptions; private PlayToAllOptions playToAllOptions; @BeforeEach public void setup() { callMedia = getMockCallMedia(202); playFileSource = new FileSource(); playFileSource.setPlaySourceCacheId("playFileSourceId"); playFileSource.setUrl("filePath"); playTextSource = new TextSource(); playTextSource.setPlaySourceCacheId("playTextSourceId"); playTextSource.setVoiceKind(VoiceKind.MALE); playTextSource.setSourceLocale("en-US"); playTextSource.setVoiceName("LULU"); playTextSource.setCustomVoiceEndpointId("customVoiceEndpointId"); playSsmlSource = new SsmlSource(); playSsmlSource.setSsmlText("<speak><voice name=\"LULU\"></voice></speak>"); playSsmlSource.setCustomVoiceEndpointId("customVoiceEndpointId"); } @Test public void playFileWithResponseTest() { playOptions = new PlayOptions(playFileSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playFileToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playFileToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextWithResponseTest() { playOptions = new PlayOptions(playTextSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlWithResponseTest() { playOptions = new PlayOptions(playSsmlSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playSsmlSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playSsmlSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void cancelAllOperationsWithResponse() { StepVerifier.create( callMedia.cancelAllMediaOperationsWithResponse()) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponse() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 1); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseWithFileSourceDtmfOptions() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); recognizeOptions.setInterToneTimeout(Duration.ofSeconds(3)); List<DtmfTone> stopDtmfTones = new ArrayList<>(); stopDtmfTones.add(DtmfTone.ZERO); stopDtmfTones.add(DtmfTone.ONE); stopDtmfTones.add(DtmfTone.TWO); recognizeOptions.setStopTones(stopDtmfTones); recognizeOptions.setRecognizeInputType(RecognizeInputType.DTMF); recognizeOptions.setPlayPrompt(new FileSource().setUrl("abc")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void startContinuousDtmfRecognitionWithResponse() { callMedia = getMockCallMedia(200); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); StepVerifier.create( callMedia.startContinuousDtmfRecognitionWithResponse( options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void stopContinuousDtmfRecognitionWithResponse() { callMedia = getMockCallMedia(200); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); StepVerifier.create( callMedia.stopContinuousDtmfRecognitionWithResponse( options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void sendDtmfWithResponse() { CallConnectionAsync callConnection = CallAutomationUnitTestBase.getCallConnectionAsync(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext("operationContext")), 202))) ); callMedia = callConnection.getCallMediaAsync(); List<DtmfTone> tones = Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()); SendDtmfTonesOptions options = new SendDtmfTonesOptions(tones, new CommunicationUserIdentifier("id")); options.setOperationContext("operationContext"); options.setOperationCallbackUrl(CallAutomationUnitTestBase.CALL_CALLBACK_URL); StepVerifier.create(callMedia.sendDtmfTonesWithResponse(options)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())).verifyComplete(); } @Test public void recognizeWithResponseWithTextSourceDtmfOptions() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); recognizeOptions.setInterToneTimeout(Duration.ofSeconds(3)); List<DtmfTone> stopDtmfTones = new ArrayList<>(); stopDtmfTones.add(DtmfTone.ZERO); stopDtmfTones.add(DtmfTone.ONE); stopDtmfTones.add(DtmfTone.TWO); recognizeOptions.setRecognizeInputType(RecognizeInputType.DTMF); recognizeOptions.setStopTones(stopDtmfTones); recognizeOptions.setPlayPrompt(new TextSource().setText("Test dmtf option with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseWithFileSourceChoiceOptions() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); recognizeChoice1.setTone(DtmfTone.ZERO); recognizeChoice2.setTone(DtmfTone.SIX); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions recognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); recognizeOptions.setRecognizeInputType(RecognizeInputType.CHOICES); recognizeOptions.setPlayPrompt(new FileSource().setUrl("abc")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechLanguage("en-US"); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextChoiceOptions() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); recognizeChoice1.setTone(DtmfTone.ZERO); recognizeChoice2.setTone(DtmfTone.THREE); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions recognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); recognizeOptions.setRecognizeInputType(RecognizeInputType.CHOICES); recognizeOptions.setPlayPrompt(new TextSource().setText("Test recognize choice with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechLanguage("en-US"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextSpeechOptions() { CallMediaRecognizeSpeechOptions recognizeOptions = new CallMediaRecognizeSpeechOptions(new CommunicationUserIdentifier("id"), Duration.ofMillis(1000)); recognizeOptions.setRecognizeInputType(RecognizeInputType.SPEECH); recognizeOptions.setPlayPrompt(new TextSource().setText("Test recognize speech or dtmf with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextSpeechOrDtmfOptions() { CallMediaRecognizeSpeechOrDtmfOptions recognizeOptions = new CallMediaRecognizeSpeechOrDtmfOptions(new CommunicationUserIdentifier("id"), 6, Duration.ofMillis(1000)); recognizeOptions.setRecognizeInputType(RecognizeInputType.SPEECH_OR_DTMF); recognizeOptions.setPlayPrompt(new SsmlSource().setSsmlText("<speak version=\"1.0\" xmlns=\"http: recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } private CallMediaAsync getMockCallMedia(int expectedStatusCode) { CallConnectionAsync callConnection = CallAutomationUnitTestBase.getCallConnectionAsync(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", expectedStatusCode))) ); return callConnection.getCallMediaAsync(); } @Test @Test public void holdWithResponseNoPromptTest() { callMedia = getMockCallMedia(200); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id")) .setPlaySourceInfo(new TextSource().setText("audio to play")); StepVerifier.create( callMedia.holdWithResponse(options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void unholdWithResponseTest() { callMedia = getMockCallMedia(200); StepVerifier.create( callMedia.unholdWithResponse( new CommunicationUserIdentifier("id"), "operationalContext" )) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void startTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StartTranscriptionOptions options = new StartTranscriptionOptions(); options.setOperationContext("operationContext"); options.setLocale("en-US"); StepVerifier.create( callMedia.startTranscriptionWithResponseAsync(options)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode()) ) .verifyComplete(); } @Test public void stopTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StopTranscriptionOptions options = new StopTranscriptionOptions(); options.setOperationContext("operationContext"); StepVerifier.create( callMedia.stopTranscriptionWithResponseAsync(options) ) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void updateTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StepVerifier.create( callMedia.updateTranscription("en-US") ).verifyComplete(); } }
Please, add a test with no prompt.
public void holdWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id"), new TextSource().setText("audio to play")); Response<Void> response = callMedia.holdWithResponse(options, null); assertEquals(response.getStatusCode(), 200); }
new TextSource().setText("audio to play"));
public void holdWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); HoldOptions options = new HoldOptions(new CommunicationUserIdentifier("id")) .setPlaySourceInfo(new TextSource().setText("audio to play")); Response<Void> response = callMedia.holdWithResponse(options, null); assertEquals(response.getStatusCode(), 200); }
class CallMediaUnitTests { private CallMedia callMedia; private FileSource playFileSource; private PlayOptions playOptions; private PlayToAllOptions playToAllOptions; private TextSource playTextSource; @BeforeEach public void setup() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 202))) ); callMedia = callConnection.getCallMedia(); playFileSource = new FileSource(); playFileSource.setPlaySourceCacheId("playTextSourceId"); playFileSource.setUrl("filePath"); playTextSource = new TextSource(); playTextSource.setPlaySourceCacheId("playTextSourceId"); playTextSource.setVoiceKind(VoiceKind.MALE); playTextSource.setSourceLocale("en-US"); playTextSource.setVoiceName("LULU"); playTextSource.setCustomVoiceEndpointId("customVoiceEndpointId"); } @Test public void playFileWithResponseTest() { playOptions = new PlayOptions(playFileSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playWithResponse(playOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playFileToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playFileToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextWithResponseTest() { playOptions = new PlayOptions(playTextSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playWithResponse(playOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void cancelAllOperationsWithResponse() { Response<Void> response = callMedia.cancelAllMediaOperationsWithResponse(Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void recognizeWithDtmfResponseTest() { CallMediaRecognizeDtmfOptions callMediaRecognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); Response<Void> response = callMedia.startRecognizingWithResponse(callMediaRecognizeOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void recognizeWithChoiceResponseTest() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions callMediaRecognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); Response<Void> response = callMedia.startRecognizingWithResponse(callMediaRecognizeOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void startContinuousDtmfRecognitionWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.startContinuousDtmfRecognitionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 200); } @Test public void stopContinuousDtmfRecognitionWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.stopContinuousDtmfRecognitionWithResponse(options, Context.NONE ); assertEquals(response.getStatusCode(), 200); } @Test public void sendDtmfTonesTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT)), 202))) ); callConnection.getCallMedia().sendDtmfTones( Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()), new CommunicationUserIdentifier("id") ); } @Test public void sendDtmfTonesWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT)), 202))) ); callMedia = callConnection.getCallMedia(); List<DtmfTone> tones = Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()); SendDtmfTonesOptions options = new SendDtmfTonesOptions(tones, new CommunicationUserIdentifier("id")); options.setOperationContext("ctx"); options.setOperationCallbackUrl(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT); Response<SendDtmfTonesResult> response = callMedia.sendDtmfTonesWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test @Test public void unholdWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); Response<Void> response = callMedia.unholdWithResponse(new CommunicationUserIdentifier("id"), "operationalContext", Context.NONE); assertEquals(response.getStatusCode(), 200); } @Test public void startTranscriptionWithResponse() { StartTranscriptionOptions options = new StartTranscriptionOptions(); options.setOperationContext("operationContext"); options.setLocale("en-US"); Response<Void> response = callMedia.startTranscriptionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void stopTranscriptionWithResponse() { StopTranscriptionOptions options = new StopTranscriptionOptions(); options.setOperationContext("operationContext"); Response<Void> response = callMedia.stopTranscriptionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void updateTranscriptionWithResponse() { Response<Void> response = callMedia.updateTranscriptionWithResponse("en-US", Context.NONE); assertEquals(response.getStatusCode(), 202); } }
class CallMediaUnitTests { private CallMedia callMedia; private FileSource playFileSource; private PlayOptions playOptions; private PlayToAllOptions playToAllOptions; private TextSource playTextSource; @BeforeEach public void setup() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 202))) ); callMedia = callConnection.getCallMedia(); playFileSource = new FileSource(); playFileSource.setPlaySourceCacheId("playTextSourceId"); playFileSource.setUrl("filePath"); playTextSource = new TextSource(); playTextSource.setPlaySourceCacheId("playTextSourceId"); playTextSource.setVoiceKind(VoiceKind.MALE); playTextSource.setSourceLocale("en-US"); playTextSource.setVoiceName("LULU"); playTextSource.setCustomVoiceEndpointId("customVoiceEndpointId"); } @Test public void playFileWithResponseTest() { playOptions = new PlayOptions(playFileSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playWithResponse(playOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playFileToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playFileToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextWithResponseTest() { playOptions = new PlayOptions(playTextSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playWithResponse(playOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void cancelAllOperationsWithResponse() { Response<Void> response = callMedia.cancelAllMediaOperationsWithResponse(Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void recognizeWithDtmfResponseTest() { CallMediaRecognizeDtmfOptions callMediaRecognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); Response<Void> response = callMedia.startRecognizingWithResponse(callMediaRecognizeOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void recognizeWithChoiceResponseTest() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions callMediaRecognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); Response<Void> response = callMedia.startRecognizingWithResponse(callMediaRecognizeOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void startContinuousDtmfRecognitionWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.startContinuousDtmfRecognitionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 200); } @Test public void stopContinuousDtmfRecognitionWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.stopContinuousDtmfRecognitionWithResponse(options, Context.NONE ); assertEquals(response.getStatusCode(), 200); } @Test public void sendDtmfTonesTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT)), 202))) ); callConnection.getCallMedia().sendDtmfTones( Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()), new CommunicationUserIdentifier("id") ); } @Test public void sendDtmfTonesWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT)), 202))) ); callMedia = callConnection.getCallMedia(); List<DtmfTone> tones = Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()); SendDtmfTonesOptions options = new SendDtmfTonesOptions(tones, new CommunicationUserIdentifier("id")); options.setOperationContext("ctx"); options.setOperationCallbackUrl(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT); Response<SendDtmfTonesResult> response = callMedia.sendDtmfTonesWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test @Test public void holdWithResponseNoPromptTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.holdWithResponse(options, null); assertEquals(response.getStatusCode(), 200); } @Test public void unholdWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); Response<Void> response = callMedia.unholdWithResponse(new CommunicationUserIdentifier("id"), "operationalContext", Context.NONE); assertEquals(response.getStatusCode(), 200); } @Test public void startTranscriptionWithResponse() { StartTranscriptionOptions options = new StartTranscriptionOptions(); options.setOperationContext("operationContext"); options.setLocale("en-US"); Response<Void> response = callMedia.startTranscriptionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void stopTranscriptionWithResponse() { StopTranscriptionOptions options = new StopTranscriptionOptions(); options.setOperationContext("operationContext"); Response<Void> response = callMedia.stopTranscriptionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void updateTranscriptionWithResponse() { Response<Void> response = callMedia.updateTranscriptionWithResponse("en-US", Context.NONE); assertEquals(response.getStatusCode(), 202); } }
added a test with no prompt.
public void holdWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id"), new TextSource().setText("audio to play")); Response<Void> response = callMedia.holdWithResponse(options, null); assertEquals(response.getStatusCode(), 200); }
new TextSource().setText("audio to play"));
public void holdWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); HoldOptions options = new HoldOptions(new CommunicationUserIdentifier("id")) .setPlaySourceInfo(new TextSource().setText("audio to play")); Response<Void> response = callMedia.holdWithResponse(options, null); assertEquals(response.getStatusCode(), 200); }
class CallMediaUnitTests { private CallMedia callMedia; private FileSource playFileSource; private PlayOptions playOptions; private PlayToAllOptions playToAllOptions; private TextSource playTextSource; @BeforeEach public void setup() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 202))) ); callMedia = callConnection.getCallMedia(); playFileSource = new FileSource(); playFileSource.setPlaySourceCacheId("playTextSourceId"); playFileSource.setUrl("filePath"); playTextSource = new TextSource(); playTextSource.setPlaySourceCacheId("playTextSourceId"); playTextSource.setVoiceKind(VoiceKind.MALE); playTextSource.setSourceLocale("en-US"); playTextSource.setVoiceName("LULU"); playTextSource.setCustomVoiceEndpointId("customVoiceEndpointId"); } @Test public void playFileWithResponseTest() { playOptions = new PlayOptions(playFileSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playWithResponse(playOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playFileToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playFileToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextWithResponseTest() { playOptions = new PlayOptions(playTextSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playWithResponse(playOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void cancelAllOperationsWithResponse() { Response<Void> response = callMedia.cancelAllMediaOperationsWithResponse(Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void recognizeWithDtmfResponseTest() { CallMediaRecognizeDtmfOptions callMediaRecognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); Response<Void> response = callMedia.startRecognizingWithResponse(callMediaRecognizeOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void recognizeWithChoiceResponseTest() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions callMediaRecognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); Response<Void> response = callMedia.startRecognizingWithResponse(callMediaRecognizeOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void startContinuousDtmfRecognitionWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.startContinuousDtmfRecognitionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 200); } @Test public void stopContinuousDtmfRecognitionWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.stopContinuousDtmfRecognitionWithResponse(options, Context.NONE ); assertEquals(response.getStatusCode(), 200); } @Test public void sendDtmfTonesTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT)), 202))) ); callConnection.getCallMedia().sendDtmfTones( Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()), new CommunicationUserIdentifier("id") ); } @Test public void sendDtmfTonesWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT)), 202))) ); callMedia = callConnection.getCallMedia(); List<DtmfTone> tones = Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()); SendDtmfTonesOptions options = new SendDtmfTonesOptions(tones, new CommunicationUserIdentifier("id")); options.setOperationContext("ctx"); options.setOperationCallbackUrl(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT); Response<SendDtmfTonesResult> response = callMedia.sendDtmfTonesWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test @Test public void unholdWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); Response<Void> response = callMedia.unholdWithResponse(new CommunicationUserIdentifier("id"), "operationalContext", Context.NONE); assertEquals(response.getStatusCode(), 200); } @Test public void startTranscriptionWithResponse() { StartTranscriptionOptions options = new StartTranscriptionOptions(); options.setOperationContext("operationContext"); options.setLocale("en-US"); Response<Void> response = callMedia.startTranscriptionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void stopTranscriptionWithResponse() { StopTranscriptionOptions options = new StopTranscriptionOptions(); options.setOperationContext("operationContext"); Response<Void> response = callMedia.stopTranscriptionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void updateTranscriptionWithResponse() { Response<Void> response = callMedia.updateTranscriptionWithResponse("en-US", Context.NONE); assertEquals(response.getStatusCode(), 202); } }
class CallMediaUnitTests { private CallMedia callMedia; private FileSource playFileSource; private PlayOptions playOptions; private PlayToAllOptions playToAllOptions; private TextSource playTextSource; @BeforeEach public void setup() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 202))) ); callMedia = callConnection.getCallMedia(); playFileSource = new FileSource(); playFileSource.setPlaySourceCacheId("playTextSourceId"); playFileSource.setUrl("filePath"); playTextSource = new TextSource(); playTextSource.setPlaySourceCacheId("playTextSourceId"); playTextSource.setVoiceKind(VoiceKind.MALE); playTextSource.setSourceLocale("en-US"); playTextSource.setVoiceName("LULU"); playTextSource.setCustomVoiceEndpointId("customVoiceEndpointId"); } @Test public void playFileWithResponseTest() { playOptions = new PlayOptions(playFileSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playWithResponse(playOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playFileToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playFileToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextWithResponseTest() { playOptions = new PlayOptions(playTextSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playWithResponse(playOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void playTextToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); Response<Void> response = callMedia.playToAllWithResponse(playToAllOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void cancelAllOperationsWithResponse() { Response<Void> response = callMedia.cancelAllMediaOperationsWithResponse(Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void recognizeWithDtmfResponseTest() { CallMediaRecognizeDtmfOptions callMediaRecognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); Response<Void> response = callMedia.startRecognizingWithResponse(callMediaRecognizeOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void recognizeWithChoiceResponseTest() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions callMediaRecognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); Response<Void> response = callMedia.startRecognizingWithResponse(callMediaRecognizeOptions, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void startContinuousDtmfRecognitionWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.startContinuousDtmfRecognitionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 200); } @Test public void stopContinuousDtmfRecognitionWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.stopContinuousDtmfRecognitionWithResponse(options, Context.NONE ); assertEquals(response.getStatusCode(), 200); } @Test public void sendDtmfTonesTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT)), 202))) ); callConnection.getCallMedia().sendDtmfTones( Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()), new CommunicationUserIdentifier("id") ); } @Test public void sendDtmfTonesWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT)), 202))) ); callMedia = callConnection.getCallMedia(); List<DtmfTone> tones = Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()); SendDtmfTonesOptions options = new SendDtmfTonesOptions(tones, new CommunicationUserIdentifier("id")); options.setOperationContext("ctx"); options.setOperationCallbackUrl(CallAutomationUnitTestBase.CALL_OPERATION_CONTEXT); Response<SendDtmfTonesResult> response = callMedia.sendDtmfTonesWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test @Test public void holdWithResponseNoPromptTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id")); Response<Void> response = callMedia.holdWithResponse(options, null); assertEquals(response.getStatusCode(), 200); } @Test public void unholdWithResponseTest() { CallConnection callConnection = CallAutomationUnitTestBase.getCallConnection(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", 200))) ); callMedia = callConnection.getCallMedia(); Response<Void> response = callMedia.unholdWithResponse(new CommunicationUserIdentifier("id"), "operationalContext", Context.NONE); assertEquals(response.getStatusCode(), 200); } @Test public void startTranscriptionWithResponse() { StartTranscriptionOptions options = new StartTranscriptionOptions(); options.setOperationContext("operationContext"); options.setLocale("en-US"); Response<Void> response = callMedia.startTranscriptionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void stopTranscriptionWithResponse() { StopTranscriptionOptions options = new StopTranscriptionOptions(); options.setOperationContext("operationContext"); Response<Void> response = callMedia.stopTranscriptionWithResponse(options, Context.NONE); assertEquals(response.getStatusCode(), 202); } @Test public void updateTranscriptionWithResponse() { Response<Void> response = callMedia.updateTranscriptionWithResponse("en-US", Context.NONE); assertEquals(response.getStatusCode(), 202); } }
added a test with no prompt.
public void holdWithResponseTest() { callMedia = getMockCallMedia(200); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id"), new TextSource().setText("audio to play")); StepVerifier.create( callMedia.holdWithResponse(options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); }
new TextSource().setText("audio to play"));
public void holdWithResponseTest() { callMedia = getMockCallMedia(200); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id")) .setPlaySourceInfo(new TextSource().setText("audio to play")); StepVerifier.create( callMedia.holdWithResponse(options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); }
class CallMediaAsyncUnitTests { private CallMediaAsync callMedia; private FileSource playFileSource; private TextSource playTextSource; private SsmlSource playSsmlSource; private PlayOptions playOptions; private PlayToAllOptions playToAllOptions; @BeforeEach public void setup() { callMedia = getMockCallMedia(202); playFileSource = new FileSource(); playFileSource.setPlaySourceCacheId("playFileSourceId"); playFileSource.setUrl("filePath"); playTextSource = new TextSource(); playTextSource.setPlaySourceCacheId("playTextSourceId"); playTextSource.setVoiceKind(VoiceKind.MALE); playTextSource.setSourceLocale("en-US"); playTextSource.setVoiceName("LULU"); playTextSource.setCustomVoiceEndpointId("customVoiceEndpointId"); playSsmlSource = new SsmlSource(); playSsmlSource.setSsmlText("<speak><voice name=\"LULU\"></voice></speak>"); playSsmlSource.setCustomVoiceEndpointId("customVoiceEndpointId"); } @Test public void playFileWithResponseTest() { playOptions = new PlayOptions(playFileSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playFileToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playFileToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextWithResponseTest() { playOptions = new PlayOptions(playTextSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlWithResponseTest() { playOptions = new PlayOptions(playSsmlSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playSsmlSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playSsmlSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void cancelAllOperationsWithResponse() { StepVerifier.create( callMedia.cancelAllMediaOperationsWithResponse()) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponse() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 1); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseWithFileSourceDtmfOptions() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); recognizeOptions.setInterToneTimeout(Duration.ofSeconds(3)); List<DtmfTone> stopDtmfTones = new ArrayList<>(); stopDtmfTones.add(DtmfTone.ZERO); stopDtmfTones.add(DtmfTone.ONE); stopDtmfTones.add(DtmfTone.TWO); recognizeOptions.setStopTones(stopDtmfTones); recognizeOptions.setRecognizeInputType(RecognizeInputType.DTMF); recognizeOptions.setPlayPrompt(new FileSource().setUrl("abc")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void startContinuousDtmfRecognitionWithResponse() { callMedia = getMockCallMedia(200); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); StepVerifier.create( callMedia.startContinuousDtmfRecognitionWithResponse( options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void stopContinuousDtmfRecognitionWithResponse() { callMedia = getMockCallMedia(200); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); StepVerifier.create( callMedia.stopContinuousDtmfRecognitionWithResponse( options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void sendDtmfWithResponse() { CallConnectionAsync callConnection = CallAutomationUnitTestBase.getCallConnectionAsync(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext("operationContext")), 202))) ); callMedia = callConnection.getCallMediaAsync(); List<DtmfTone> tones = Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()); SendDtmfTonesOptions options = new SendDtmfTonesOptions(tones, new CommunicationUserIdentifier("id")); options.setOperationContext("operationContext"); options.setOperationCallbackUrl(CallAutomationUnitTestBase.CALL_CALLBACK_URL); StepVerifier.create(callMedia.sendDtmfTonesWithResponse(options)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())).verifyComplete(); } @Test public void recognizeWithResponseWithTextSourceDtmfOptions() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); recognizeOptions.setInterToneTimeout(Duration.ofSeconds(3)); List<DtmfTone> stopDtmfTones = new ArrayList<>(); stopDtmfTones.add(DtmfTone.ZERO); stopDtmfTones.add(DtmfTone.ONE); stopDtmfTones.add(DtmfTone.TWO); recognizeOptions.setRecognizeInputType(RecognizeInputType.DTMF); recognizeOptions.setStopTones(stopDtmfTones); recognizeOptions.setPlayPrompt(new TextSource().setText("Test dmtf option with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseWithFileSourceChoiceOptions() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); recognizeChoice1.setTone(DtmfTone.ZERO); recognizeChoice2.setTone(DtmfTone.SIX); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions recognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); recognizeOptions.setRecognizeInputType(RecognizeInputType.CHOICES); recognizeOptions.setPlayPrompt(new FileSource().setUrl("abc")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechLanguage("en-US"); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextChoiceOptions() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); recognizeChoice1.setTone(DtmfTone.ZERO); recognizeChoice2.setTone(DtmfTone.THREE); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions recognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); recognizeOptions.setRecognizeInputType(RecognizeInputType.CHOICES); recognizeOptions.setPlayPrompt(new TextSource().setText("Test recognize choice with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechLanguage("en-US"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextSpeechOptions() { CallMediaRecognizeSpeechOptions recognizeOptions = new CallMediaRecognizeSpeechOptions(new CommunicationUserIdentifier("id"), Duration.ofMillis(1000)); recognizeOptions.setRecognizeInputType(RecognizeInputType.SPEECH); recognizeOptions.setPlayPrompt(new TextSource().setText("Test recognize speech or dtmf with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextSpeechOrDtmfOptions() { CallMediaRecognizeSpeechOrDtmfOptions recognizeOptions = new CallMediaRecognizeSpeechOrDtmfOptions(new CommunicationUserIdentifier("id"), 6, Duration.ofMillis(1000)); recognizeOptions.setRecognizeInputType(RecognizeInputType.SPEECH_OR_DTMF); recognizeOptions.setPlayPrompt(new SsmlSource().setSsmlText("<speak version=\"1.0\" xmlns=\"http: recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } private CallMediaAsync getMockCallMedia(int expectedStatusCode) { CallConnectionAsync callConnection = CallAutomationUnitTestBase.getCallConnectionAsync(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", expectedStatusCode))) ); return callConnection.getCallMediaAsync(); } @Test @Test public void unholdWithResponseTest() { callMedia = getMockCallMedia(200); StepVerifier.create( callMedia.unholdWithResponse( new CommunicationUserIdentifier("id"), "operationalContext" )) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void startTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StartTranscriptionOptions options = new StartTranscriptionOptions(); options.setOperationContext("operationContext"); options.setLocale("en-US"); StepVerifier.create( callMedia.startTranscriptionWithResponseAsync(options)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode()) ) .verifyComplete(); } @Test public void stopTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StopTranscriptionOptions options = new StopTranscriptionOptions(); options.setOperationContext("operationContext"); StepVerifier.create( callMedia.stopTranscriptionWithResponseAsync(options) ) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void updateTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StepVerifier.create( callMedia.updateTranscription("en-US") ).verifyComplete(); } }
class CallMediaAsyncUnitTests { private CallMediaAsync callMedia; private FileSource playFileSource; private TextSource playTextSource; private SsmlSource playSsmlSource; private PlayOptions playOptions; private PlayToAllOptions playToAllOptions; @BeforeEach public void setup() { callMedia = getMockCallMedia(202); playFileSource = new FileSource(); playFileSource.setPlaySourceCacheId("playFileSourceId"); playFileSource.setUrl("filePath"); playTextSource = new TextSource(); playTextSource.setPlaySourceCacheId("playTextSourceId"); playTextSource.setVoiceKind(VoiceKind.MALE); playTextSource.setSourceLocale("en-US"); playTextSource.setVoiceName("LULU"); playTextSource.setCustomVoiceEndpointId("customVoiceEndpointId"); playSsmlSource = new SsmlSource(); playSsmlSource.setSsmlText("<speak><voice name=\"LULU\"></voice></speak>"); playSsmlSource.setCustomVoiceEndpointId("customVoiceEndpointId"); } @Test public void playFileWithResponseTest() { playOptions = new PlayOptions(playFileSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playFileToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playFileToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playFileSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextWithResponseTest() { playOptions = new PlayOptions(playTextSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playTextToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playTextSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlWithResponseTest() { playOptions = new PlayOptions(playSsmlSource, Collections.singletonList(new CommunicationUserIdentifier("id"))) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playWithResponse(playOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlToAllWithResponseTest() { playToAllOptions = new PlayToAllOptions(playSsmlSource) .setLoop(false) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void playSsmlToAllWithBargeInWithResponseTest() { playToAllOptions = new PlayToAllOptions(playSsmlSource) .setLoop(false) .setInterruptCallMediaOperation(true) .setOperationContext("operationContext"); StepVerifier.create( callMedia.playToAllWithResponse(playToAllOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void cancelAllOperationsWithResponse() { StepVerifier.create( callMedia.cancelAllMediaOperationsWithResponse()) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponse() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 1); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseWithFileSourceDtmfOptions() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); recognizeOptions.setInterToneTimeout(Duration.ofSeconds(3)); List<DtmfTone> stopDtmfTones = new ArrayList<>(); stopDtmfTones.add(DtmfTone.ZERO); stopDtmfTones.add(DtmfTone.ONE); stopDtmfTones.add(DtmfTone.TWO); recognizeOptions.setStopTones(stopDtmfTones); recognizeOptions.setRecognizeInputType(RecognizeInputType.DTMF); recognizeOptions.setPlayPrompt(new FileSource().setUrl("abc")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void startContinuousDtmfRecognitionWithResponse() { callMedia = getMockCallMedia(200); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); StepVerifier.create( callMedia.startContinuousDtmfRecognitionWithResponse( options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void stopContinuousDtmfRecognitionWithResponse() { callMedia = getMockCallMedia(200); ContinuousDtmfRecognitionOptions options = new ContinuousDtmfRecognitionOptions(new CommunicationUserIdentifier("id")); StepVerifier.create( callMedia.stopContinuousDtmfRecognitionWithResponse( options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void sendDtmfWithResponse() { CallConnectionAsync callConnection = CallAutomationUnitTestBase.getCallConnectionAsync(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>( CallAutomationUnitTestBase.serializeObject(new SendDtmfTonesResultInternal().setOperationContext("operationContext")), 202))) ); callMedia = callConnection.getCallMediaAsync(); List<DtmfTone> tones = Stream.of(DtmfTone.ONE, DtmfTone.TWO, DtmfTone.THREE).collect(Collectors.toList()); SendDtmfTonesOptions options = new SendDtmfTonesOptions(tones, new CommunicationUserIdentifier("id")); options.setOperationContext("operationContext"); options.setOperationCallbackUrl(CallAutomationUnitTestBase.CALL_CALLBACK_URL); StepVerifier.create(callMedia.sendDtmfTonesWithResponse(options)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())).verifyComplete(); } @Test public void recognizeWithResponseWithTextSourceDtmfOptions() { CallMediaRecognizeDtmfOptions recognizeOptions = new CallMediaRecognizeDtmfOptions(new CommunicationUserIdentifier("id"), 5); recognizeOptions.setInterToneTimeout(Duration.ofSeconds(3)); List<DtmfTone> stopDtmfTones = new ArrayList<>(); stopDtmfTones.add(DtmfTone.ZERO); stopDtmfTones.add(DtmfTone.ONE); stopDtmfTones.add(DtmfTone.TWO); recognizeOptions.setRecognizeInputType(RecognizeInputType.DTMF); recognizeOptions.setStopTones(stopDtmfTones); recognizeOptions.setPlayPrompt(new TextSource().setText("Test dmtf option with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseWithFileSourceChoiceOptions() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); recognizeChoice1.setTone(DtmfTone.ZERO); recognizeChoice2.setTone(DtmfTone.SIX); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions recognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); recognizeOptions.setRecognizeInputType(RecognizeInputType.CHOICES); recognizeOptions.setPlayPrompt(new FileSource().setUrl("abc")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechLanguage("en-US"); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextChoiceOptions() { RecognitionChoice recognizeChoice1 = new RecognitionChoice(); RecognitionChoice recognizeChoice2 = new RecognitionChoice(); recognizeChoice1.setTone(DtmfTone.ZERO); recognizeChoice2.setTone(DtmfTone.THREE); List<RecognitionChoice> recognizeChoices = new ArrayList<>( Arrays.asList(recognizeChoice1, recognizeChoice2) ); CallMediaRecognizeChoiceOptions recognizeOptions = new CallMediaRecognizeChoiceOptions(new CommunicationUserIdentifier("id"), recognizeChoices); recognizeOptions.setRecognizeInputType(RecognizeInputType.CHOICES); recognizeOptions.setPlayPrompt(new TextSource().setText("Test recognize choice with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechLanguage("en-US"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextSpeechOptions() { CallMediaRecognizeSpeechOptions recognizeOptions = new CallMediaRecognizeSpeechOptions(new CommunicationUserIdentifier("id"), Duration.ofMillis(1000)); recognizeOptions.setRecognizeInputType(RecognizeInputType.SPEECH); recognizeOptions.setPlayPrompt(new TextSource().setText("Test recognize speech or dtmf with text source.")); recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void recognizeWithResponseTextSpeechOrDtmfOptions() { CallMediaRecognizeSpeechOrDtmfOptions recognizeOptions = new CallMediaRecognizeSpeechOrDtmfOptions(new CommunicationUserIdentifier("id"), 6, Duration.ofMillis(1000)); recognizeOptions.setRecognizeInputType(RecognizeInputType.SPEECH_OR_DTMF); recognizeOptions.setPlayPrompt(new SsmlSource().setSsmlText("<speak version=\"1.0\" xmlns=\"http: recognizeOptions.setInterruptCallMediaOperation(true); recognizeOptions.setStopCurrentOperations(true); recognizeOptions.setOperationContext("operationContext"); recognizeOptions.setInterruptPrompt(true); recognizeOptions.setInitialSilenceTimeout(Duration.ofSeconds(4)); recognizeOptions.setSpeechModelEndpointId("customModelEndpointId"); StepVerifier.create( callMedia.startRecognizingWithResponse(recognizeOptions)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } private CallMediaAsync getMockCallMedia(int expectedStatusCode) { CallConnectionAsync callConnection = CallAutomationUnitTestBase.getCallConnectionAsync(new ArrayList<>( Collections.singletonList(new AbstractMap.SimpleEntry<>("", expectedStatusCode))) ); return callConnection.getCallMediaAsync(); } @Test @Test public void holdWithResponseNoPromptTest() { callMedia = getMockCallMedia(200); HoldOptions options = new HoldOptions( new CommunicationUserIdentifier("id")) .setPlaySourceInfo(new TextSource().setText("audio to play")); StepVerifier.create( callMedia.holdWithResponse(options)) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void unholdWithResponseTest() { callMedia = getMockCallMedia(200); StepVerifier.create( callMedia.unholdWithResponse( new CommunicationUserIdentifier("id"), "operationalContext" )) .consumeNextWith(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } @Test public void startTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StartTranscriptionOptions options = new StartTranscriptionOptions(); options.setOperationContext("operationContext"); options.setLocale("en-US"); StepVerifier.create( callMedia.startTranscriptionWithResponseAsync(options)) .consumeNextWith(response -> assertEquals(202, response.getStatusCode()) ) .verifyComplete(); } @Test public void stopTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StopTranscriptionOptions options = new StopTranscriptionOptions(); options.setOperationContext("operationContext"); StepVerifier.create( callMedia.stopTranscriptionWithResponseAsync(options) ) .consumeNextWith(response -> assertEquals(202, response.getStatusCode())) .verifyComplete(); } @Test public void updateTranscriptionWithResponse() { callMedia = getMockCallMedia(202); StepVerifier.create( callMedia.updateTranscription("en-US") ).verifyComplete(); } }
nit: it'd be more readable if we had a method like ```java private Throwable checkState(State s) { Throwable error = null; if (s == State.EMPTY) { error = logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (s == State.DISPOSED) { error = logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, resourceType))); } return error; } ``` then did ```java Throwable error = checkState(state.get();` if (error != null) { sink(error); return; } ``` It'd make it clear that there are no side-effects in this operation. Also we'd not use exception handling for logic. Also could it still be possible for an error to happen before we do `getSession` on the line 238? If so, why do we need this one?
Mono<ProtonChannel> channel(final String name, Duration timeout) { final Mono<ProtonChannel> channel = Mono.create(sink -> { if (name == null) { sink.error(new NullPointerException("'name' cannot be null.")); return; } try { getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session; try { session = getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } final String senderName = name + ":sender"; final String receiverName = name + ":receiver"; sink.success(new ProtonChannel(name, session.sender(senderName), session.receiver(receiverName))); }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); sink.error(retriableAmqpError(null, message, e)); } else { sink.error(e); } } }); return channel.timeout(timeout, Mono.error(() -> { final String message = String.format(OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT, getConnectionId(), getName(), name); return retriableAmqpError(TIMEOUT_ERROR, message, null); })); }
getSession("channel");
Mono<ProtonChannel> channel(final String name, Duration timeout) { final Mono<ProtonChannel> channel = Mono.create(sink -> { if (name == null) { sink.error(new NullPointerException("'name' cannot be null.")); return; } try { resource.get().validate(logger, "channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session; try { session = getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } final String senderName = name + ":sender"; final String receiverName = name + ":receiver"; sink.success(new ProtonChannel(name, session.sender(senderName), session.receiver(receiverName))); }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); sink.error(retriableAmqpError(null, message, e)); } else { sink.error(e); } } }); return channel.timeout(timeout, Mono.error(() -> { final String message = String.format(OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT, getConnectionId(), getName(), name); return retriableAmqpError(TIMEOUT_ERROR, message, null); })); }
class ProtonSession { private static final String SESSION_NOT_OPENED = "session has not been opened."; private static final String NOT_OPENING_DISPOSED_SESSION = "session is already disposed, not opening."; private static final String DISPOSED_MESSAGE_FORMAT = "Cannot create %s from a closed session."; private static final String REACTOR_CLOSED_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] connection-reactor is disposed."; private static final String OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] obtaining channel (%s) timed out."; private final AtomicReference<State> state = new AtomicReference<>(State.EMPTY); private final AtomicBoolean opened = new AtomicBoolean(false); private final Sinks.Empty<Void> openAwaiter = Sinks.empty(); private final Connection connection; private final ReactorProvider reactorProvider; private final SessionHandler handler; private final ClientLogger logger; /** * Creates a ProtonSession. * * @param connectionId the id of the QPid Proton-j Connection hosting the session. * @param hostname the host name of the broker that the QPid Proton-j Connection hosting * the session is connected to. * @param connection the QPid Proton-j Connection hosting the session. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher. * @param sessionName the session name. * @param openTimeout the session open timeout. * @param logger the client logger. */ ProtonSession(String connectionId, String hostname, Connection connection, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, String sessionName, Duration openTimeout, ClientLogger logger) { this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); Objects.requireNonNull(handlerProvider, "'handlerProvider' cannot be null."); this.handler = handlerProvider.createSessionHandler(connectionId, hostname, sessionName, openTimeout); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); } /** * Gets the session name. * * @return the session name. */ String getName() { return handler.getSessionName(); } /** * Gets the identifier of the QPid Proton-j Connection hosting the session. * * @return the connection identifier. */ String getConnectionId() { return handler.getConnectionId(); } /** * Gets the host name of the broker that the QPid Proton-j Connection facilitating the session * is connected to. * * @return the hostname. */ String getHostname() { return handler.getHostname(); } /** * Gets the error context of the session. * * @return the error context. */ AmqpErrorContext getErrorContext() { return handler.getErrorContext(); } /** * Gets the connectivity states of the session. * * @return the session's connectivity states. */ Flux<EndpointState> getEndpointStates() { return handler.getEndpointStates(); } /** * Gets the reactor dispatcher provider associated with the session. * <p> * Any operation (e.g., obtaining sender, receiver) on the session must be invoked on the reactor dispatcher. * </p> * * @return the reactor dispatcher provider. */ ReactorProvider getReactorProvider() { return reactorProvider; } /** * Opens the session in the QPid Proton-j Connection. * <p> * The session open attempt is made upon the first subscription, once opened later subscriptions will complete * immediately, i.e. there is an open-only-once semantics. * </p> * <p> * If the session (or parent Qpid Proton-j connection) is disposed after opening, any later operation attempts * (e.g., creating sender, receiver, channel) will fail. * </p> * <p> * By design, no re-open attempt will be made within this type. Lifetime of a {@link ProtonSession} instance is * scoped to life time of one low level Qpid Proton-j session instance it manages, which is scoped within the * life time of qpid Proton-j Connection hosting it. Re-establishing session requires querying the connection-cache * to obtain the latest connection (may not be same as the connection facilitated this session) then hosting and * opening a new {@link ProtonSession} on it. It means, upon a retriable {@link AmqpException} from any APIs (to * create sender, receiver, channel) in this type, the call sites needs to obtain a new {@link ProtonSession} * by polling the connection-cache. * </p> * * @return a mono that completes once the session is opened. * <p> * <ul>the mono can terminates with retriable {@link AmqpException} if * <li>the session disposal happened while opening,</li> * <li>or the connection reactor thread got shutdown while opening.</li> * </ul> * </p> */ Mono<Void> open() { if (opened.getAndSet(true)) { return openAwaiter.asMono(); } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session = connection.session(); BaseHandler.setHandler(session, handler); session.open(); logger.atInfo() .addKeyValue(SESSION_NAME_KEY, handler.getSessionName()) .log("session local open scheduled."); if (state.compareAndSet(State.EMPTY, new State(session))) { openAwaiter.emitEmpty(FAIL_FAST); } else { session.close(); if (state.get() == State.DISPOSED) { openAwaiter.emitError(new ProtonSessionClosedException(NOT_OPENING_DISPOSED_SESSION), FAIL_FAST); } else { openAwaiter.emitError(new IllegalStateException("session is already opened."), FAIL_FAST); } } }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); openAwaiter.emitError(retriableAmqpError(null, message, e), FAIL_FAST); } else { openAwaiter.emitError(e, FAIL_FAST); } } return openAwaiter.asMono(); } /** * Gets a bidirectional channel on the session. * <p> * A channel consists of a sender link and a receiver link, and is used for management operations where a sender * link is used to send a request to the broker and a receiver link gets the associated response from the broker. * </p> * * @param name the channel name, which is used as the name prefix for sender link and receiver link in the channel. * @param timeout the timeout for obtaining the channel. * * @return a mono that completes with a {@link ProtonChannel} once the channel is created in the session. * <p> * <ul> * <li>the mono terminates with {@link IllegalStateException} if the session is not opened yet via {@link * <li>the mono terminates with * <ul> * <li>a retriable {@link ProtonSessionClosedException} if the session is disposed,</li> * <li>a retriable {@link AmqpException} if obtaining channel timeout,</li> * <li>or a retriable {@link AmqpException} if the connection reactor thread is shutdown.</li> * </ul> * </li> * </ul> * </p> */ /** * Gets a QPid Proton-j sender on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the sender was made before opening the session. * @throws ProtonSessionClosedException (a retriable {@link AmqpException}) if the session was disposed. */ Sender senderUnsafe(String name) { final Session session = getSession("sender link"); return session.sender(name); } /** * Gets a QPid Proton-j receiver on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the receiver was made before opening the session. * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ Receiver receiverUnsafe(String name) { final Session session = getSession("receive link"); return session.receiver(name); } /** * Begin the disposal by locally closing the underlying QPid Proton-j session. * * @param errorCondition the error condition to close the session with. */ void beginClose(ErrorCondition errorCondition) { final State s = state.getAndSet(State.DISPOSED); if (s == State.EMPTY || s == State.DISPOSED) { return; } final Session session = s.get(); if (session.getLocalState() != EndpointState.CLOSED) { session.close(); if (errorCondition != null && session.getCondition() == null) { session.setCondition(errorCondition); } } } /** * Completes the disposal by closing the {@link SessionHandler}. */ void endClose() { handler.close(); } /** * Obtain the underlying QPid Proton-j {@link Session} atomically. * * @param resourceType the type of the resource (e.g., sender, receiver, channel) that the call site want to host * on the obtained session. The provided string value is used only to form error message for any exception. * * @return the QPid Proton-j session. * @throws IllegalStateException if the attempt to obtain the session was made before opening via {@link * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ private Session getSession(String resourceType) { final State s = state.get(); if (s == State.EMPTY) { throw logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (s == State.DISPOSED) { throw logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, resourceType))); } return s.get(); } /** * Creates a retriable AMQP exception. * <p> * The call sites uses this method to translate a session unavailability "event" (session disposed, session operation * timed-out or connection being closed) to a retriable error. While the "event" is transient, recovering from it * by creating a new session on current connection or on a new connection needs to be done not by this class or * the parent 'ReactorConnection' owning this ProtonSession but by the downstream. E.g., the downstream Consumer, * Producer Client that has access to the chain to propagate retry request to top level V2 ReactorConnectionCache. * </p> * @param condition the error condition. * @param message the error message. * @param cause the actual cause of error. * @return the retriable AMQP exception. */ private AmqpException retriableAmqpError(AmqpErrorCondition condition, String message, Throwable cause) { return new AmqpException(true, condition, message, cause, handler.getErrorContext()); } /** * Type representing a bidirectional channel hosted on the QPid Proton-j session. * <p> * The {@link RequestResponseChannel} underneath uses an instance of {@link ProtonChannel} for the bi-directional * communication with the broker. * </p> */ static final class ProtonChannel { private final String name; private final Sender sender; private final Receiver receiver; /** * Creates a ProtonChannel. * * @param name the channel name. * @param sender the sender endpoint of the channel. * @param receiver the receiver endpoint of the channel. */ ProtonChannel(String name, Sender sender, Receiver receiver) { this.name = name; this.sender = sender; this.receiver = receiver; } /** * Gets the channel name. * * @return the channel name. */ String getName() { return name; } /** * Gets the sender endpoint of the channel. * * @return the channel's sender endpoint. */ Sender getSender() { return sender; } /** * Gets the receiver endpoint of the channel. * * @return the channel's receiver endpoint. */ Receiver getReceiver() { return receiver; } } /** * A retriable {@link AmqpException} indicating session is disposed. */ static final class ProtonSessionClosedException extends AmqpException { private ProtonSessionClosedException(String message) { super(true, message, null); } } /** * A type to atomically access the underlying QPid Proton-j {@link Session} that {@link ProtonSession} manages. */ private static final class State { private static final State EMPTY = new State(); private static final State DISPOSED = new State(); private final Session session; private State() { this.session = null; } private State(Session session) { this.session = Objects.requireNonNull(session, "'session' cannot be null."); } private Session get() { assert this != EMPTY; return this.session; } } }
class ProtonSession { private static final String SESSION_NOT_OPENED = "session has not been opened."; private static final String NOT_OPENING_DISPOSED_SESSION = "session is already disposed, not opening."; private static final String DISPOSED_MESSAGE_FORMAT = "Cannot create %s from a closed session."; private static final String REACTOR_CLOSED_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] connection-reactor is disposed."; private static final String OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] obtaining channel (%s) timed out."; private final AtomicReference<Resource> resource = new AtomicReference<>(Resource.EMPTY); private final AtomicBoolean opened = new AtomicBoolean(false); private final Sinks.Empty<Void> openAwaiter = Sinks.empty(); private final Connection connection; private final ReactorProvider reactorProvider; private final SessionHandler handler; private final String id; private final ClientLogger logger; /** * Creates a ProtonSession. * * @param connectionId the id of the QPid Proton-j Connection hosting the session. * @param hostname the host name of the broker that the QPid Proton-j Connection hosting * the session is connected to. * @param connection the QPid Proton-j Connection hosting the session. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher. * @param sessionName the session name. * @param openTimeout the session open timeout. * @param logger the client logger. */ ProtonSession(String connectionId, String hostname, Connection connection, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, String sessionName, Duration openTimeout, ClientLogger logger) { this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); Objects.requireNonNull(handlerProvider, "'handlerProvider' cannot be null."); this.handler = handlerProvider.createSessionHandler(connectionId, hostname, sessionName, openTimeout); this.id = handler.getId(); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); } /** * Gets the id, useful for the logging purposes. * * @return the id. */ String getId() { return id; } /** * Gets the session name. * * @return the session name. */ String getName() { return handler.getSessionName(); } /** * Gets the identifier of the QPid Proton-j Connection hosting the session. * * @return the connection identifier. */ String getConnectionId() { return handler.getConnectionId(); } /** * Gets the host name of the broker that the QPid Proton-j Connection facilitating the session * is connected to. * * @return the hostname. */ String getHostname() { return handler.getHostname(); } /** * Gets the error context of the session. * * @return the error context. */ AmqpErrorContext getErrorContext() { return handler.getErrorContext(); } /** * Gets the connectivity states of the session. * * @return the session's connectivity states. */ Flux<EndpointState> getEndpointStates() { return handler.getEndpointStates(); } /** * Gets the reactor dispatcher provider associated with the session. * <p> * Any operation (e.g., obtaining sender, receiver) on the session must be invoked on the reactor dispatcher. * </p> * * @return the reactor dispatcher provider. */ ReactorProvider getReactorProvider() { return reactorProvider; } /** * Opens the session in the QPid Proton-j Connection. * <p> * The session open attempt is made upon the first subscription, once opened later subscriptions will complete * immediately, i.e. there is an open-only-once semantics. * </p> * <p> * If the session (or parent Qpid Proton-j connection) is disposed after opening, any later operation attempts * (e.g., creating sender, receiver, channel) will fail. * </p> * <p> * By design, no re-open attempt will be made within this type. Lifetime of a {@link ProtonSession} instance is * scoped to life time of one low level Qpid Proton-j session instance it manages, which is scoped within the * life time of qpid Proton-j Connection hosting it. Re-establishing session requires querying the connection-cache * to obtain the latest connection (may not be same as the connection facilitated this session) then hosting and * opening a new {@link ProtonSession} on it. It means, upon a retriable {@link AmqpException} from any APIs (to * create sender, receiver, channel) in this type, the call sites needs to obtain a new {@link ProtonSession} * by polling the connection-cache. * </p> * * @return a mono that completes once the session is opened. * <p> * <ul>the mono can terminates with retriable {@link AmqpException} if * <li>the session disposal happened while opening,</li> * <li>or the connection reactor thread got shutdown while opening.</li> * </ul> * </p> */ Mono<Void> open() { if (opened.getAndSet(true)) { return openAwaiter.asMono(); } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session = connection.session(); BaseHandler.setHandler(session, handler); session.open(); logger.atInfo() .addKeyValue(SESSION_NAME_KEY, handler.getSessionName()) .addKeyValue(SESSION_ID_KEY, id) .log("session local open scheduled."); if (resource.compareAndSet(Resource.EMPTY, new Resource(session))) { openAwaiter.emitEmpty(FAIL_FAST); } else { session.close(); if (resource.get() == Resource.DISPOSED) { openAwaiter.emitError(new ProtonSessionClosedException(NOT_OPENING_DISPOSED_SESSION), FAIL_FAST); } else { openAwaiter.emitError(new IllegalStateException("session is already opened."), FAIL_FAST); } } }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); openAwaiter.emitError(retriableAmqpError(null, message, e), FAIL_FAST); } else { openAwaiter.emitError(e, FAIL_FAST); } } return openAwaiter.asMono(); } /** * Gets a bidirectional channel on the session. * <p> * A channel consists of a sender link and a receiver link, and is used for management operations where a sender * link is used to send a request to the broker and a receiver link gets the associated response from the broker. * </p> * * @param name the channel name, which is used as the name prefix for sender link and receiver link in the channel. * @param timeout the timeout for obtaining the channel. * * @return a mono that completes with a {@link ProtonChannel} once the channel is created in the session. * <p> * <ul> * <li>the mono terminates with {@link IllegalStateException} if the session is not opened yet via {@link * <li>the mono terminates with * <ul> * <li>a retriable {@link ProtonSessionClosedException} if the session is disposed,</li> * <li>a retriable {@link AmqpException} if obtaining channel timeout,</li> * <li>or a retriable {@link AmqpException} if the connection reactor thread is shutdown.</li> * </ul> * </li> * </ul> * </p> */ /** * Gets a QPid Proton-j sender on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the sender was made before opening the session. * @throws ProtonSessionClosedException (a retriable {@link AmqpException}) if the session was disposed. */ Sender senderUnsafe(String name) { final Session session = getSession("sender link"); return session.sender(name); } /** * Gets a QPid Proton-j receiver on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the receiver was made before opening the session. * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ Receiver receiverUnsafe(String name) { final Session session = getSession("receive link"); return session.receiver(name); } /** * Begin the disposal by locally closing the underlying QPid Proton-j session. * * @param errorCondition the error condition to close the session with. */ void beginClose(ErrorCondition errorCondition) { final Resource s = resource.getAndSet(Resource.DISPOSED); if (s == Resource.EMPTY || s == Resource.DISPOSED) { return; } final Session session = s.value(); if (session.getLocalState() != EndpointState.CLOSED) { session.close(); if (errorCondition != null && session.getCondition() == null) { session.setCondition(errorCondition); } } } /** * Completes the disposal by closing the {@link SessionHandler}. */ void endClose() { handler.close(); } /** * Obtain the underlying QPid Proton-j {@link Session} atomically. * * @param endpointType the type of the endpoint (e.g., sender, receiver, channel) that the call site want to host * on the obtained session. The provided string value is used only to form error message for any exception. * * @return the QPid Proton-j session. * @throws IllegalStateException if the attempt to obtain the session was made before opening via {@link * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ private Session getSession(String endpointType) { final Resource r = resource.get(); r.validate(logger, endpointType); return r.value(); } /** * Creates a retriable AMQP exception. * <p> * The call sites uses this method to translate a session unavailability "event" (session disposed, session operation * timed-out or connection being closed) to a retriable error. While the "event" is transient, recovering from it * by creating a new session on current connection or on a new connection needs to be done not by this class or * the parent 'ReactorConnection' owning this ProtonSession but by the downstream. E.g., the downstream Consumer, * Producer Client that has access to the chain to propagate retry request to top level V2 ReactorConnectionCache. * </p> * @param condition the error condition. * @param message the error message. * @param cause the actual cause of error. * @return the retriable AMQP exception. */ private AmqpException retriableAmqpError(AmqpErrorCondition condition, String message, Throwable cause) { return new AmqpException(true, condition, message, cause, handler.getErrorContext()); } /** * Type representing a bidirectional channel hosted on the QPid Proton-j session. * <p> * The {@link RequestResponseChannel} underneath uses an instance of {@link ProtonChannel} for the bi-directional * communication with the broker. * </p> */ static final class ProtonChannel { private final String name; private final Sender sender; private final Receiver receiver; /** * Creates a ProtonChannel. * * @param name the channel name. * @param sender the sender endpoint of the channel. * @param receiver the receiver endpoint of the channel. */ ProtonChannel(String name, Sender sender, Receiver receiver) { this.name = name; this.sender = sender; this.receiver = receiver; } /** * Gets the channel name. * * @return the channel name. */ String getName() { return name; } /** * Gets the sender endpoint of the channel. * * @return the channel's sender endpoint. */ Sender getSender() { return sender; } /** * Gets the receiver endpoint of the channel. * * @return the channel's receiver endpoint. */ Receiver getReceiver() { return receiver; } } /** * A retriable {@link AmqpException} indicating session is disposed. */ static final class ProtonSessionClosedException extends AmqpException { private ProtonSessionClosedException(String message) { super(true, message, null); } } /** * A type to store the underlying QPid Proton-j {@link Session} that the {@link ProtonSession} manages. * The {@link ProtonSession} access this resource atomically. */ private static final class Resource { private static final Resource EMPTY = new Resource(); private static final Resource DISPOSED = new Resource(); private final Session session; /** * Creates a Resource initialized with a QPid Proton-j {@link Session}. * * @param session the session. */ Resource(Session session) { this.session = Objects.requireNonNull(session, "'session' cannot be null."); } /** * Gets the underlying QPid Proton-j {@link Session}. * * @return the session. */ Session value() { assert this != EMPTY; return this.session; } /** * Check that if resource is in a valid state i.e., if it holds a session. An error is thrown if the resource * is not initialized with a session or disposed. * * @param logger the logger to log the error in case of invalid state. * @param endpointType the type of the endpoint (e.g., sender, receiver, channel) that the call site want to * host on the underlying session. The provided string value is used only to form error message. * @throws IllegalStateException if the resource is not initialized with a session. * @throws ProtonSessionClosedException if the resource is disposed. */ void validate(ClientLogger logger, String endpointType) { if (this == Resource.EMPTY) { throw logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (this == Resource.DISPOSED) { throw logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, endpointType))); } } /** * Constructor for the static EMPTY and DISPOSED state. */ private Resource() { this.session = null; } } }
Thank you, yes, a separate method like the one you proposed will improve the readability.
Mono<ProtonChannel> channel(final String name, Duration timeout) { final Mono<ProtonChannel> channel = Mono.create(sink -> { if (name == null) { sink.error(new NullPointerException("'name' cannot be null.")); return; } try { getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session; try { session = getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } final String senderName = name + ":sender"; final String receiverName = name + ":receiver"; sink.success(new ProtonChannel(name, session.sender(senderName), session.receiver(receiverName))); }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); sink.error(retriableAmqpError(null, message, e)); } else { sink.error(e); } } }); return channel.timeout(timeout, Mono.error(() -> { final String message = String.format(OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT, getConnectionId(), getName(), name); return retriableAmqpError(TIMEOUT_ERROR, message, null); })); }
getSession("channel");
Mono<ProtonChannel> channel(final String name, Duration timeout) { final Mono<ProtonChannel> channel = Mono.create(sink -> { if (name == null) { sink.error(new NullPointerException("'name' cannot be null.")); return; } try { resource.get().validate(logger, "channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session; try { session = getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } final String senderName = name + ":sender"; final String receiverName = name + ":receiver"; sink.success(new ProtonChannel(name, session.sender(senderName), session.receiver(receiverName))); }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); sink.error(retriableAmqpError(null, message, e)); } else { sink.error(e); } } }); return channel.timeout(timeout, Mono.error(() -> { final String message = String.format(OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT, getConnectionId(), getName(), name); return retriableAmqpError(TIMEOUT_ERROR, message, null); })); }
class ProtonSession { private static final String SESSION_NOT_OPENED = "session has not been opened."; private static final String NOT_OPENING_DISPOSED_SESSION = "session is already disposed, not opening."; private static final String DISPOSED_MESSAGE_FORMAT = "Cannot create %s from a closed session."; private static final String REACTOR_CLOSED_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] connection-reactor is disposed."; private static final String OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] obtaining channel (%s) timed out."; private final AtomicReference<State> state = new AtomicReference<>(State.EMPTY); private final AtomicBoolean opened = new AtomicBoolean(false); private final Sinks.Empty<Void> openAwaiter = Sinks.empty(); private final Connection connection; private final ReactorProvider reactorProvider; private final SessionHandler handler; private final ClientLogger logger; /** * Creates a ProtonSession. * * @param connectionId the id of the QPid Proton-j Connection hosting the session. * @param hostname the host name of the broker that the QPid Proton-j Connection hosting * the session is connected to. * @param connection the QPid Proton-j Connection hosting the session. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher. * @param sessionName the session name. * @param openTimeout the session open timeout. * @param logger the client logger. */ ProtonSession(String connectionId, String hostname, Connection connection, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, String sessionName, Duration openTimeout, ClientLogger logger) { this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); Objects.requireNonNull(handlerProvider, "'handlerProvider' cannot be null."); this.handler = handlerProvider.createSessionHandler(connectionId, hostname, sessionName, openTimeout); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); } /** * Gets the session name. * * @return the session name. */ String getName() { return handler.getSessionName(); } /** * Gets the identifier of the QPid Proton-j Connection hosting the session. * * @return the connection identifier. */ String getConnectionId() { return handler.getConnectionId(); } /** * Gets the host name of the broker that the QPid Proton-j Connection facilitating the session * is connected to. * * @return the hostname. */ String getHostname() { return handler.getHostname(); } /** * Gets the error context of the session. * * @return the error context. */ AmqpErrorContext getErrorContext() { return handler.getErrorContext(); } /** * Gets the connectivity states of the session. * * @return the session's connectivity states. */ Flux<EndpointState> getEndpointStates() { return handler.getEndpointStates(); } /** * Gets the reactor dispatcher provider associated with the session. * <p> * Any operation (e.g., obtaining sender, receiver) on the session must be invoked on the reactor dispatcher. * </p> * * @return the reactor dispatcher provider. */ ReactorProvider getReactorProvider() { return reactorProvider; } /** * Opens the session in the QPid Proton-j Connection. * <p> * The session open attempt is made upon the first subscription, once opened later subscriptions will complete * immediately, i.e. there is an open-only-once semantics. * </p> * <p> * If the session (or parent Qpid Proton-j connection) is disposed after opening, any later operation attempts * (e.g., creating sender, receiver, channel) will fail. * </p> * <p> * By design, no re-open attempt will be made within this type. Lifetime of a {@link ProtonSession} instance is * scoped to life time of one low level Qpid Proton-j session instance it manages, which is scoped within the * life time of qpid Proton-j Connection hosting it. Re-establishing session requires querying the connection-cache * to obtain the latest connection (may not be same as the connection facilitated this session) then hosting and * opening a new {@link ProtonSession} on it. It means, upon a retriable {@link AmqpException} from any APIs (to * create sender, receiver, channel) in this type, the call sites needs to obtain a new {@link ProtonSession} * by polling the connection-cache. * </p> * * @return a mono that completes once the session is opened. * <p> * <ul>the mono can terminates with retriable {@link AmqpException} if * <li>the session disposal happened while opening,</li> * <li>or the connection reactor thread got shutdown while opening.</li> * </ul> * </p> */ Mono<Void> open() { if (opened.getAndSet(true)) { return openAwaiter.asMono(); } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session = connection.session(); BaseHandler.setHandler(session, handler); session.open(); logger.atInfo() .addKeyValue(SESSION_NAME_KEY, handler.getSessionName()) .log("session local open scheduled."); if (state.compareAndSet(State.EMPTY, new State(session))) { openAwaiter.emitEmpty(FAIL_FAST); } else { session.close(); if (state.get() == State.DISPOSED) { openAwaiter.emitError(new ProtonSessionClosedException(NOT_OPENING_DISPOSED_SESSION), FAIL_FAST); } else { openAwaiter.emitError(new IllegalStateException("session is already opened."), FAIL_FAST); } } }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); openAwaiter.emitError(retriableAmqpError(null, message, e), FAIL_FAST); } else { openAwaiter.emitError(e, FAIL_FAST); } } return openAwaiter.asMono(); } /** * Gets a bidirectional channel on the session. * <p> * A channel consists of a sender link and a receiver link, and is used for management operations where a sender * link is used to send a request to the broker and a receiver link gets the associated response from the broker. * </p> * * @param name the channel name, which is used as the name prefix for sender link and receiver link in the channel. * @param timeout the timeout for obtaining the channel. * * @return a mono that completes with a {@link ProtonChannel} once the channel is created in the session. * <p> * <ul> * <li>the mono terminates with {@link IllegalStateException} if the session is not opened yet via {@link * <li>the mono terminates with * <ul> * <li>a retriable {@link ProtonSessionClosedException} if the session is disposed,</li> * <li>a retriable {@link AmqpException} if obtaining channel timeout,</li> * <li>or a retriable {@link AmqpException} if the connection reactor thread is shutdown.</li> * </ul> * </li> * </ul> * </p> */ /** * Gets a QPid Proton-j sender on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the sender was made before opening the session. * @throws ProtonSessionClosedException (a retriable {@link AmqpException}) if the session was disposed. */ Sender senderUnsafe(String name) { final Session session = getSession("sender link"); return session.sender(name); } /** * Gets a QPid Proton-j receiver on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the receiver was made before opening the session. * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ Receiver receiverUnsafe(String name) { final Session session = getSession("receive link"); return session.receiver(name); } /** * Begin the disposal by locally closing the underlying QPid Proton-j session. * * @param errorCondition the error condition to close the session with. */ void beginClose(ErrorCondition errorCondition) { final State s = state.getAndSet(State.DISPOSED); if (s == State.EMPTY || s == State.DISPOSED) { return; } final Session session = s.get(); if (session.getLocalState() != EndpointState.CLOSED) { session.close(); if (errorCondition != null && session.getCondition() == null) { session.setCondition(errorCondition); } } } /** * Completes the disposal by closing the {@link SessionHandler}. */ void endClose() { handler.close(); } /** * Obtain the underlying QPid Proton-j {@link Session} atomically. * * @param resourceType the type of the resource (e.g., sender, receiver, channel) that the call site want to host * on the obtained session. The provided string value is used only to form error message for any exception. * * @return the QPid Proton-j session. * @throws IllegalStateException if the attempt to obtain the session was made before opening via {@link * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ private Session getSession(String resourceType) { final State s = state.get(); if (s == State.EMPTY) { throw logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (s == State.DISPOSED) { throw logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, resourceType))); } return s.get(); } /** * Creates a retriable AMQP exception. * <p> * The call sites uses this method to translate a session unavailability "event" (session disposed, session operation * timed-out or connection being closed) to a retriable error. While the "event" is transient, recovering from it * by creating a new session on current connection or on a new connection needs to be done not by this class or * the parent 'ReactorConnection' owning this ProtonSession but by the downstream. E.g., the downstream Consumer, * Producer Client that has access to the chain to propagate retry request to top level V2 ReactorConnectionCache. * </p> * @param condition the error condition. * @param message the error message. * @param cause the actual cause of error. * @return the retriable AMQP exception. */ private AmqpException retriableAmqpError(AmqpErrorCondition condition, String message, Throwable cause) { return new AmqpException(true, condition, message, cause, handler.getErrorContext()); } /** * Type representing a bidirectional channel hosted on the QPid Proton-j session. * <p> * The {@link RequestResponseChannel} underneath uses an instance of {@link ProtonChannel} for the bi-directional * communication with the broker. * </p> */ static final class ProtonChannel { private final String name; private final Sender sender; private final Receiver receiver; /** * Creates a ProtonChannel. * * @param name the channel name. * @param sender the sender endpoint of the channel. * @param receiver the receiver endpoint of the channel. */ ProtonChannel(String name, Sender sender, Receiver receiver) { this.name = name; this.sender = sender; this.receiver = receiver; } /** * Gets the channel name. * * @return the channel name. */ String getName() { return name; } /** * Gets the sender endpoint of the channel. * * @return the channel's sender endpoint. */ Sender getSender() { return sender; } /** * Gets the receiver endpoint of the channel. * * @return the channel's receiver endpoint. */ Receiver getReceiver() { return receiver; } } /** * A retriable {@link AmqpException} indicating session is disposed. */ static final class ProtonSessionClosedException extends AmqpException { private ProtonSessionClosedException(String message) { super(true, message, null); } } /** * A type to atomically access the underlying QPid Proton-j {@link Session} that {@link ProtonSession} manages. */ private static final class State { private static final State EMPTY = new State(); private static final State DISPOSED = new State(); private final Session session; private State() { this.session = null; } private State(Session session) { this.session = Objects.requireNonNull(session, "'session' cannot be null."); } private Session get() { assert this != EMPTY; return this.session; } } }
class ProtonSession { private static final String SESSION_NOT_OPENED = "session has not been opened."; private static final String NOT_OPENING_DISPOSED_SESSION = "session is already disposed, not opening."; private static final String DISPOSED_MESSAGE_FORMAT = "Cannot create %s from a closed session."; private static final String REACTOR_CLOSED_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] connection-reactor is disposed."; private static final String OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] obtaining channel (%s) timed out."; private final AtomicReference<Resource> resource = new AtomicReference<>(Resource.EMPTY); private final AtomicBoolean opened = new AtomicBoolean(false); private final Sinks.Empty<Void> openAwaiter = Sinks.empty(); private final Connection connection; private final ReactorProvider reactorProvider; private final SessionHandler handler; private final String id; private final ClientLogger logger; /** * Creates a ProtonSession. * * @param connectionId the id of the QPid Proton-j Connection hosting the session. * @param hostname the host name of the broker that the QPid Proton-j Connection hosting * the session is connected to. * @param connection the QPid Proton-j Connection hosting the session. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher. * @param sessionName the session name. * @param openTimeout the session open timeout. * @param logger the client logger. */ ProtonSession(String connectionId, String hostname, Connection connection, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, String sessionName, Duration openTimeout, ClientLogger logger) { this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); Objects.requireNonNull(handlerProvider, "'handlerProvider' cannot be null."); this.handler = handlerProvider.createSessionHandler(connectionId, hostname, sessionName, openTimeout); this.id = handler.getId(); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); } /** * Gets the id, useful for the logging purposes. * * @return the id. */ String getId() { return id; } /** * Gets the session name. * * @return the session name. */ String getName() { return handler.getSessionName(); } /** * Gets the identifier of the QPid Proton-j Connection hosting the session. * * @return the connection identifier. */ String getConnectionId() { return handler.getConnectionId(); } /** * Gets the host name of the broker that the QPid Proton-j Connection facilitating the session * is connected to. * * @return the hostname. */ String getHostname() { return handler.getHostname(); } /** * Gets the error context of the session. * * @return the error context. */ AmqpErrorContext getErrorContext() { return handler.getErrorContext(); } /** * Gets the connectivity states of the session. * * @return the session's connectivity states. */ Flux<EndpointState> getEndpointStates() { return handler.getEndpointStates(); } /** * Gets the reactor dispatcher provider associated with the session. * <p> * Any operation (e.g., obtaining sender, receiver) on the session must be invoked on the reactor dispatcher. * </p> * * @return the reactor dispatcher provider. */ ReactorProvider getReactorProvider() { return reactorProvider; } /** * Opens the session in the QPid Proton-j Connection. * <p> * The session open attempt is made upon the first subscription, once opened later subscriptions will complete * immediately, i.e. there is an open-only-once semantics. * </p> * <p> * If the session (or parent Qpid Proton-j connection) is disposed after opening, any later operation attempts * (e.g., creating sender, receiver, channel) will fail. * </p> * <p> * By design, no re-open attempt will be made within this type. Lifetime of a {@link ProtonSession} instance is * scoped to life time of one low level Qpid Proton-j session instance it manages, which is scoped within the * life time of qpid Proton-j Connection hosting it. Re-establishing session requires querying the connection-cache * to obtain the latest connection (may not be same as the connection facilitated this session) then hosting and * opening a new {@link ProtonSession} on it. It means, upon a retriable {@link AmqpException} from any APIs (to * create sender, receiver, channel) in this type, the call sites needs to obtain a new {@link ProtonSession} * by polling the connection-cache. * </p> * * @return a mono that completes once the session is opened. * <p> * <ul>the mono can terminates with retriable {@link AmqpException} if * <li>the session disposal happened while opening,</li> * <li>or the connection reactor thread got shutdown while opening.</li> * </ul> * </p> */ Mono<Void> open() { if (opened.getAndSet(true)) { return openAwaiter.asMono(); } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session = connection.session(); BaseHandler.setHandler(session, handler); session.open(); logger.atInfo() .addKeyValue(SESSION_NAME_KEY, handler.getSessionName()) .addKeyValue(SESSION_ID_KEY, id) .log("session local open scheduled."); if (resource.compareAndSet(Resource.EMPTY, new Resource(session))) { openAwaiter.emitEmpty(FAIL_FAST); } else { session.close(); if (resource.get() == Resource.DISPOSED) { openAwaiter.emitError(new ProtonSessionClosedException(NOT_OPENING_DISPOSED_SESSION), FAIL_FAST); } else { openAwaiter.emitError(new IllegalStateException("session is already opened."), FAIL_FAST); } } }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); openAwaiter.emitError(retriableAmqpError(null, message, e), FAIL_FAST); } else { openAwaiter.emitError(e, FAIL_FAST); } } return openAwaiter.asMono(); } /** * Gets a bidirectional channel on the session. * <p> * A channel consists of a sender link and a receiver link, and is used for management operations where a sender * link is used to send a request to the broker and a receiver link gets the associated response from the broker. * </p> * * @param name the channel name, which is used as the name prefix for sender link and receiver link in the channel. * @param timeout the timeout for obtaining the channel. * * @return a mono that completes with a {@link ProtonChannel} once the channel is created in the session. * <p> * <ul> * <li>the mono terminates with {@link IllegalStateException} if the session is not opened yet via {@link * <li>the mono terminates with * <ul> * <li>a retriable {@link ProtonSessionClosedException} if the session is disposed,</li> * <li>a retriable {@link AmqpException} if obtaining channel timeout,</li> * <li>or a retriable {@link AmqpException} if the connection reactor thread is shutdown.</li> * </ul> * </li> * </ul> * </p> */ /** * Gets a QPid Proton-j sender on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the sender was made before opening the session. * @throws ProtonSessionClosedException (a retriable {@link AmqpException}) if the session was disposed. */ Sender senderUnsafe(String name) { final Session session = getSession("sender link"); return session.sender(name); } /** * Gets a QPid Proton-j receiver on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the receiver was made before opening the session. * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ Receiver receiverUnsafe(String name) { final Session session = getSession("receive link"); return session.receiver(name); } /** * Begin the disposal by locally closing the underlying QPid Proton-j session. * * @param errorCondition the error condition to close the session with. */ void beginClose(ErrorCondition errorCondition) { final Resource s = resource.getAndSet(Resource.DISPOSED); if (s == Resource.EMPTY || s == Resource.DISPOSED) { return; } final Session session = s.value(); if (session.getLocalState() != EndpointState.CLOSED) { session.close(); if (errorCondition != null && session.getCondition() == null) { session.setCondition(errorCondition); } } } /** * Completes the disposal by closing the {@link SessionHandler}. */ void endClose() { handler.close(); } /** * Obtain the underlying QPid Proton-j {@link Session} atomically. * * @param endpointType the type of the endpoint (e.g., sender, receiver, channel) that the call site want to host * on the obtained session. The provided string value is used only to form error message for any exception. * * @return the QPid Proton-j session. * @throws IllegalStateException if the attempt to obtain the session was made before opening via {@link * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ private Session getSession(String endpointType) { final Resource r = resource.get(); r.validate(logger, endpointType); return r.value(); } /** * Creates a retriable AMQP exception. * <p> * The call sites uses this method to translate a session unavailability "event" (session disposed, session operation * timed-out or connection being closed) to a retriable error. While the "event" is transient, recovering from it * by creating a new session on current connection or on a new connection needs to be done not by this class or * the parent 'ReactorConnection' owning this ProtonSession but by the downstream. E.g., the downstream Consumer, * Producer Client that has access to the chain to propagate retry request to top level V2 ReactorConnectionCache. * </p> * @param condition the error condition. * @param message the error message. * @param cause the actual cause of error. * @return the retriable AMQP exception. */ private AmqpException retriableAmqpError(AmqpErrorCondition condition, String message, Throwable cause) { return new AmqpException(true, condition, message, cause, handler.getErrorContext()); } /** * Type representing a bidirectional channel hosted on the QPid Proton-j session. * <p> * The {@link RequestResponseChannel} underneath uses an instance of {@link ProtonChannel} for the bi-directional * communication with the broker. * </p> */ static final class ProtonChannel { private final String name; private final Sender sender; private final Receiver receiver; /** * Creates a ProtonChannel. * * @param name the channel name. * @param sender the sender endpoint of the channel. * @param receiver the receiver endpoint of the channel. */ ProtonChannel(String name, Sender sender, Receiver receiver) { this.name = name; this.sender = sender; this.receiver = receiver; } /** * Gets the channel name. * * @return the channel name. */ String getName() { return name; } /** * Gets the sender endpoint of the channel. * * @return the channel's sender endpoint. */ Sender getSender() { return sender; } /** * Gets the receiver endpoint of the channel. * * @return the channel's receiver endpoint. */ Receiver getReceiver() { return receiver; } } /** * A retriable {@link AmqpException} indicating session is disposed. */ static final class ProtonSessionClosedException extends AmqpException { private ProtonSessionClosedException(String message) { super(true, message, null); } } /** * A type to store the underlying QPid Proton-j {@link Session} that the {@link ProtonSession} manages. * The {@link ProtonSession} access this resource atomically. */ private static final class Resource { private static final Resource EMPTY = new Resource(); private static final Resource DISPOSED = new Resource(); private final Session session; /** * Creates a Resource initialized with a QPid Proton-j {@link Session}. * * @param session the session. */ Resource(Session session) { this.session = Objects.requireNonNull(session, "'session' cannot be null."); } /** * Gets the underlying QPid Proton-j {@link Session}. * * @return the session. */ Session value() { assert this != EMPTY; return this.session; } /** * Check that if resource is in a valid state i.e., if it holds a session. An error is thrown if the resource * is not initialized with a session or disposed. * * @param logger the logger to log the error in case of invalid state. * @param endpointType the type of the endpoint (e.g., sender, receiver, channel) that the call site want to * host on the underlying session. The provided string value is used only to form error message. * @throws IllegalStateException if the resource is not initialized with a session. * @throws ProtonSessionClosedException if the resource is disposed. */ void validate(ClientLogger logger, String endpointType) { if (this == Resource.EMPTY) { throw logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (this == Resource.DISPOSED) { throw logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, endpointType))); } } /** * Constructor for the static EMPTY and DISPOSED state. */ private Resource() { this.session = null; } } }
The reason for doing this check on entry is to see if we can "fail fast in the current thread", before scheduling the work to Qpid-thread. So yes, we can still encounter error by the time Qpid-thread picks the work, but we can save a potential unnecessary thread-hopping-cost with that entry check.
Mono<ProtonChannel> channel(final String name, Duration timeout) { final Mono<ProtonChannel> channel = Mono.create(sink -> { if (name == null) { sink.error(new NullPointerException("'name' cannot be null.")); return; } try { getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session; try { session = getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } final String senderName = name + ":sender"; final String receiverName = name + ":receiver"; sink.success(new ProtonChannel(name, session.sender(senderName), session.receiver(receiverName))); }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); sink.error(retriableAmqpError(null, message, e)); } else { sink.error(e); } } }); return channel.timeout(timeout, Mono.error(() -> { final String message = String.format(OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT, getConnectionId(), getName(), name); return retriableAmqpError(TIMEOUT_ERROR, message, null); })); }
getSession("channel");
Mono<ProtonChannel> channel(final String name, Duration timeout) { final Mono<ProtonChannel> channel = Mono.create(sink -> { if (name == null) { sink.error(new NullPointerException("'name' cannot be null.")); return; } try { resource.get().validate(logger, "channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session; try { session = getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } final String senderName = name + ":sender"; final String receiverName = name + ":receiver"; sink.success(new ProtonChannel(name, session.sender(senderName), session.receiver(receiverName))); }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); sink.error(retriableAmqpError(null, message, e)); } else { sink.error(e); } } }); return channel.timeout(timeout, Mono.error(() -> { final String message = String.format(OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT, getConnectionId(), getName(), name); return retriableAmqpError(TIMEOUT_ERROR, message, null); })); }
class ProtonSession { private static final String SESSION_NOT_OPENED = "session has not been opened."; private static final String NOT_OPENING_DISPOSED_SESSION = "session is already disposed, not opening."; private static final String DISPOSED_MESSAGE_FORMAT = "Cannot create %s from a closed session."; private static final String REACTOR_CLOSED_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] connection-reactor is disposed."; private static final String OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] obtaining channel (%s) timed out."; private final AtomicReference<State> state = new AtomicReference<>(State.EMPTY); private final AtomicBoolean opened = new AtomicBoolean(false); private final Sinks.Empty<Void> openAwaiter = Sinks.empty(); private final Connection connection; private final ReactorProvider reactorProvider; private final SessionHandler handler; private final ClientLogger logger; /** * Creates a ProtonSession. * * @param connectionId the id of the QPid Proton-j Connection hosting the session. * @param hostname the host name of the broker that the QPid Proton-j Connection hosting * the session is connected to. * @param connection the QPid Proton-j Connection hosting the session. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher. * @param sessionName the session name. * @param openTimeout the session open timeout. * @param logger the client logger. */ ProtonSession(String connectionId, String hostname, Connection connection, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, String sessionName, Duration openTimeout, ClientLogger logger) { this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); Objects.requireNonNull(handlerProvider, "'handlerProvider' cannot be null."); this.handler = handlerProvider.createSessionHandler(connectionId, hostname, sessionName, openTimeout); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); } /** * Gets the session name. * * @return the session name. */ String getName() { return handler.getSessionName(); } /** * Gets the identifier of the QPid Proton-j Connection hosting the session. * * @return the connection identifier. */ String getConnectionId() { return handler.getConnectionId(); } /** * Gets the host name of the broker that the QPid Proton-j Connection facilitating the session * is connected to. * * @return the hostname. */ String getHostname() { return handler.getHostname(); } /** * Gets the error context of the session. * * @return the error context. */ AmqpErrorContext getErrorContext() { return handler.getErrorContext(); } /** * Gets the connectivity states of the session. * * @return the session's connectivity states. */ Flux<EndpointState> getEndpointStates() { return handler.getEndpointStates(); } /** * Gets the reactor dispatcher provider associated with the session. * <p> * Any operation (e.g., obtaining sender, receiver) on the session must be invoked on the reactor dispatcher. * </p> * * @return the reactor dispatcher provider. */ ReactorProvider getReactorProvider() { return reactorProvider; } /** * Opens the session in the QPid Proton-j Connection. * <p> * The session open attempt is made upon the first subscription, once opened later subscriptions will complete * immediately, i.e. there is an open-only-once semantics. * </p> * <p> * If the session (or parent Qpid Proton-j connection) is disposed after opening, any later operation attempts * (e.g., creating sender, receiver, channel) will fail. * </p> * <p> * By design, no re-open attempt will be made within this type. Lifetime of a {@link ProtonSession} instance is * scoped to life time of one low level Qpid Proton-j session instance it manages, which is scoped within the * life time of qpid Proton-j Connection hosting it. Re-establishing session requires querying the connection-cache * to obtain the latest connection (may not be same as the connection facilitated this session) then hosting and * opening a new {@link ProtonSession} on it. It means, upon a retriable {@link AmqpException} from any APIs (to * create sender, receiver, channel) in this type, the call sites needs to obtain a new {@link ProtonSession} * by polling the connection-cache. * </p> * * @return a mono that completes once the session is opened. * <p> * <ul>the mono can terminates with retriable {@link AmqpException} if * <li>the session disposal happened while opening,</li> * <li>or the connection reactor thread got shutdown while opening.</li> * </ul> * </p> */ Mono<Void> open() { if (opened.getAndSet(true)) { return openAwaiter.asMono(); } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session = connection.session(); BaseHandler.setHandler(session, handler); session.open(); logger.atInfo() .addKeyValue(SESSION_NAME_KEY, handler.getSessionName()) .log("session local open scheduled."); if (state.compareAndSet(State.EMPTY, new State(session))) { openAwaiter.emitEmpty(FAIL_FAST); } else { session.close(); if (state.get() == State.DISPOSED) { openAwaiter.emitError(new ProtonSessionClosedException(NOT_OPENING_DISPOSED_SESSION), FAIL_FAST); } else { openAwaiter.emitError(new IllegalStateException("session is already opened."), FAIL_FAST); } } }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); openAwaiter.emitError(retriableAmqpError(null, message, e), FAIL_FAST); } else { openAwaiter.emitError(e, FAIL_FAST); } } return openAwaiter.asMono(); } /** * Gets a bidirectional channel on the session. * <p> * A channel consists of a sender link and a receiver link, and is used for management operations where a sender * link is used to send a request to the broker and a receiver link gets the associated response from the broker. * </p> * * @param name the channel name, which is used as the name prefix for sender link and receiver link in the channel. * @param timeout the timeout for obtaining the channel. * * @return a mono that completes with a {@link ProtonChannel} once the channel is created in the session. * <p> * <ul> * <li>the mono terminates with {@link IllegalStateException} if the session is not opened yet via {@link * <li>the mono terminates with * <ul> * <li>a retriable {@link ProtonSessionClosedException} if the session is disposed,</li> * <li>a retriable {@link AmqpException} if obtaining channel timeout,</li> * <li>or a retriable {@link AmqpException} if the connection reactor thread is shutdown.</li> * </ul> * </li> * </ul> * </p> */ /** * Gets a QPid Proton-j sender on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the sender was made before opening the session. * @throws ProtonSessionClosedException (a retriable {@link AmqpException}) if the session was disposed. */ Sender senderUnsafe(String name) { final Session session = getSession("sender link"); return session.sender(name); } /** * Gets a QPid Proton-j receiver on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the receiver was made before opening the session. * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ Receiver receiverUnsafe(String name) { final Session session = getSession("receive link"); return session.receiver(name); } /** * Begin the disposal by locally closing the underlying QPid Proton-j session. * * @param errorCondition the error condition to close the session with. */ void beginClose(ErrorCondition errorCondition) { final State s = state.getAndSet(State.DISPOSED); if (s == State.EMPTY || s == State.DISPOSED) { return; } final Session session = s.get(); if (session.getLocalState() != EndpointState.CLOSED) { session.close(); if (errorCondition != null && session.getCondition() == null) { session.setCondition(errorCondition); } } } /** * Completes the disposal by closing the {@link SessionHandler}. */ void endClose() { handler.close(); } /** * Obtain the underlying QPid Proton-j {@link Session} atomically. * * @param resourceType the type of the resource (e.g., sender, receiver, channel) that the call site want to host * on the obtained session. The provided string value is used only to form error message for any exception. * * @return the QPid Proton-j session. * @throws IllegalStateException if the attempt to obtain the session was made before opening via {@link * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ private Session getSession(String resourceType) { final State s = state.get(); if (s == State.EMPTY) { throw logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (s == State.DISPOSED) { throw logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, resourceType))); } return s.get(); } /** * Creates a retriable AMQP exception. * <p> * The call sites uses this method to translate a session unavailability "event" (session disposed, session operation * timed-out or connection being closed) to a retriable error. While the "event" is transient, recovering from it * by creating a new session on current connection or on a new connection needs to be done not by this class or * the parent 'ReactorConnection' owning this ProtonSession but by the downstream. E.g., the downstream Consumer, * Producer Client that has access to the chain to propagate retry request to top level V2 ReactorConnectionCache. * </p> * @param condition the error condition. * @param message the error message. * @param cause the actual cause of error. * @return the retriable AMQP exception. */ private AmqpException retriableAmqpError(AmqpErrorCondition condition, String message, Throwable cause) { return new AmqpException(true, condition, message, cause, handler.getErrorContext()); } /** * Type representing a bidirectional channel hosted on the QPid Proton-j session. * <p> * The {@link RequestResponseChannel} underneath uses an instance of {@link ProtonChannel} for the bi-directional * communication with the broker. * </p> */ static final class ProtonChannel { private final String name; private final Sender sender; private final Receiver receiver; /** * Creates a ProtonChannel. * * @param name the channel name. * @param sender the sender endpoint of the channel. * @param receiver the receiver endpoint of the channel. */ ProtonChannel(String name, Sender sender, Receiver receiver) { this.name = name; this.sender = sender; this.receiver = receiver; } /** * Gets the channel name. * * @return the channel name. */ String getName() { return name; } /** * Gets the sender endpoint of the channel. * * @return the channel's sender endpoint. */ Sender getSender() { return sender; } /** * Gets the receiver endpoint of the channel. * * @return the channel's receiver endpoint. */ Receiver getReceiver() { return receiver; } } /** * A retriable {@link AmqpException} indicating session is disposed. */ static final class ProtonSessionClosedException extends AmqpException { private ProtonSessionClosedException(String message) { super(true, message, null); } } /** * A type to atomically access the underlying QPid Proton-j {@link Session} that {@link ProtonSession} manages. */ private static final class State { private static final State EMPTY = new State(); private static final State DISPOSED = new State(); private final Session session; private State() { this.session = null; } private State(Session session) { this.session = Objects.requireNonNull(session, "'session' cannot be null."); } private Session get() { assert this != EMPTY; return this.session; } } }
class ProtonSession { private static final String SESSION_NOT_OPENED = "session has not been opened."; private static final String NOT_OPENING_DISPOSED_SESSION = "session is already disposed, not opening."; private static final String DISPOSED_MESSAGE_FORMAT = "Cannot create %s from a closed session."; private static final String REACTOR_CLOSED_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] connection-reactor is disposed."; private static final String OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] obtaining channel (%s) timed out."; private final AtomicReference<Resource> resource = new AtomicReference<>(Resource.EMPTY); private final AtomicBoolean opened = new AtomicBoolean(false); private final Sinks.Empty<Void> openAwaiter = Sinks.empty(); private final Connection connection; private final ReactorProvider reactorProvider; private final SessionHandler handler; private final String id; private final ClientLogger logger; /** * Creates a ProtonSession. * * @param connectionId the id of the QPid Proton-j Connection hosting the session. * @param hostname the host name of the broker that the QPid Proton-j Connection hosting * the session is connected to. * @param connection the QPid Proton-j Connection hosting the session. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher. * @param sessionName the session name. * @param openTimeout the session open timeout. * @param logger the client logger. */ ProtonSession(String connectionId, String hostname, Connection connection, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, String sessionName, Duration openTimeout, ClientLogger logger) { this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); Objects.requireNonNull(handlerProvider, "'handlerProvider' cannot be null."); this.handler = handlerProvider.createSessionHandler(connectionId, hostname, sessionName, openTimeout); this.id = handler.getId(); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); } /** * Gets the id, useful for the logging purposes. * * @return the id. */ String getId() { return id; } /** * Gets the session name. * * @return the session name. */ String getName() { return handler.getSessionName(); } /** * Gets the identifier of the QPid Proton-j Connection hosting the session. * * @return the connection identifier. */ String getConnectionId() { return handler.getConnectionId(); } /** * Gets the host name of the broker that the QPid Proton-j Connection facilitating the session * is connected to. * * @return the hostname. */ String getHostname() { return handler.getHostname(); } /** * Gets the error context of the session. * * @return the error context. */ AmqpErrorContext getErrorContext() { return handler.getErrorContext(); } /** * Gets the connectivity states of the session. * * @return the session's connectivity states. */ Flux<EndpointState> getEndpointStates() { return handler.getEndpointStates(); } /** * Gets the reactor dispatcher provider associated with the session. * <p> * Any operation (e.g., obtaining sender, receiver) on the session must be invoked on the reactor dispatcher. * </p> * * @return the reactor dispatcher provider. */ ReactorProvider getReactorProvider() { return reactorProvider; } /** * Opens the session in the QPid Proton-j Connection. * <p> * The session open attempt is made upon the first subscription, once opened later subscriptions will complete * immediately, i.e. there is an open-only-once semantics. * </p> * <p> * If the session (or parent Qpid Proton-j connection) is disposed after opening, any later operation attempts * (e.g., creating sender, receiver, channel) will fail. * </p> * <p> * By design, no re-open attempt will be made within this type. Lifetime of a {@link ProtonSession} instance is * scoped to life time of one low level Qpid Proton-j session instance it manages, which is scoped within the * life time of qpid Proton-j Connection hosting it. Re-establishing session requires querying the connection-cache * to obtain the latest connection (may not be same as the connection facilitated this session) then hosting and * opening a new {@link ProtonSession} on it. It means, upon a retriable {@link AmqpException} from any APIs (to * create sender, receiver, channel) in this type, the call sites needs to obtain a new {@link ProtonSession} * by polling the connection-cache. * </p> * * @return a mono that completes once the session is opened. * <p> * <ul>the mono can terminates with retriable {@link AmqpException} if * <li>the session disposal happened while opening,</li> * <li>or the connection reactor thread got shutdown while opening.</li> * </ul> * </p> */ Mono<Void> open() { if (opened.getAndSet(true)) { return openAwaiter.asMono(); } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session = connection.session(); BaseHandler.setHandler(session, handler); session.open(); logger.atInfo() .addKeyValue(SESSION_NAME_KEY, handler.getSessionName()) .addKeyValue(SESSION_ID_KEY, id) .log("session local open scheduled."); if (resource.compareAndSet(Resource.EMPTY, new Resource(session))) { openAwaiter.emitEmpty(FAIL_FAST); } else { session.close(); if (resource.get() == Resource.DISPOSED) { openAwaiter.emitError(new ProtonSessionClosedException(NOT_OPENING_DISPOSED_SESSION), FAIL_FAST); } else { openAwaiter.emitError(new IllegalStateException("session is already opened."), FAIL_FAST); } } }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); openAwaiter.emitError(retriableAmqpError(null, message, e), FAIL_FAST); } else { openAwaiter.emitError(e, FAIL_FAST); } } return openAwaiter.asMono(); } /** * Gets a bidirectional channel on the session. * <p> * A channel consists of a sender link and a receiver link, and is used for management operations where a sender * link is used to send a request to the broker and a receiver link gets the associated response from the broker. * </p> * * @param name the channel name, which is used as the name prefix for sender link and receiver link in the channel. * @param timeout the timeout for obtaining the channel. * * @return a mono that completes with a {@link ProtonChannel} once the channel is created in the session. * <p> * <ul> * <li>the mono terminates with {@link IllegalStateException} if the session is not opened yet via {@link * <li>the mono terminates with * <ul> * <li>a retriable {@link ProtonSessionClosedException} if the session is disposed,</li> * <li>a retriable {@link AmqpException} if obtaining channel timeout,</li> * <li>or a retriable {@link AmqpException} if the connection reactor thread is shutdown.</li> * </ul> * </li> * </ul> * </p> */ /** * Gets a QPid Proton-j sender on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the sender was made before opening the session. * @throws ProtonSessionClosedException (a retriable {@link AmqpException}) if the session was disposed. */ Sender senderUnsafe(String name) { final Session session = getSession("sender link"); return session.sender(name); } /** * Gets a QPid Proton-j receiver on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the receiver was made before opening the session. * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ Receiver receiverUnsafe(String name) { final Session session = getSession("receive link"); return session.receiver(name); } /** * Begin the disposal by locally closing the underlying QPid Proton-j session. * * @param errorCondition the error condition to close the session with. */ void beginClose(ErrorCondition errorCondition) { final Resource s = resource.getAndSet(Resource.DISPOSED); if (s == Resource.EMPTY || s == Resource.DISPOSED) { return; } final Session session = s.value(); if (session.getLocalState() != EndpointState.CLOSED) { session.close(); if (errorCondition != null && session.getCondition() == null) { session.setCondition(errorCondition); } } } /** * Completes the disposal by closing the {@link SessionHandler}. */ void endClose() { handler.close(); } /** * Obtain the underlying QPid Proton-j {@link Session} atomically. * * @param endpointType the type of the endpoint (e.g., sender, receiver, channel) that the call site want to host * on the obtained session. The provided string value is used only to form error message for any exception. * * @return the QPid Proton-j session. * @throws IllegalStateException if the attempt to obtain the session was made before opening via {@link * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ private Session getSession(String endpointType) { final Resource r = resource.get(); r.validate(logger, endpointType); return r.value(); } /** * Creates a retriable AMQP exception. * <p> * The call sites uses this method to translate a session unavailability "event" (session disposed, session operation * timed-out or connection being closed) to a retriable error. While the "event" is transient, recovering from it * by creating a new session on current connection or on a new connection needs to be done not by this class or * the parent 'ReactorConnection' owning this ProtonSession but by the downstream. E.g., the downstream Consumer, * Producer Client that has access to the chain to propagate retry request to top level V2 ReactorConnectionCache. * </p> * @param condition the error condition. * @param message the error message. * @param cause the actual cause of error. * @return the retriable AMQP exception. */ private AmqpException retriableAmqpError(AmqpErrorCondition condition, String message, Throwable cause) { return new AmqpException(true, condition, message, cause, handler.getErrorContext()); } /** * Type representing a bidirectional channel hosted on the QPid Proton-j session. * <p> * The {@link RequestResponseChannel} underneath uses an instance of {@link ProtonChannel} for the bi-directional * communication with the broker. * </p> */ static final class ProtonChannel { private final String name; private final Sender sender; private final Receiver receiver; /** * Creates a ProtonChannel. * * @param name the channel name. * @param sender the sender endpoint of the channel. * @param receiver the receiver endpoint of the channel. */ ProtonChannel(String name, Sender sender, Receiver receiver) { this.name = name; this.sender = sender; this.receiver = receiver; } /** * Gets the channel name. * * @return the channel name. */ String getName() { return name; } /** * Gets the sender endpoint of the channel. * * @return the channel's sender endpoint. */ Sender getSender() { return sender; } /** * Gets the receiver endpoint of the channel. * * @return the channel's receiver endpoint. */ Receiver getReceiver() { return receiver; } } /** * A retriable {@link AmqpException} indicating session is disposed. */ static final class ProtonSessionClosedException extends AmqpException { private ProtonSessionClosedException(String message) { super(true, message, null); } } /** * A type to store the underlying QPid Proton-j {@link Session} that the {@link ProtonSession} manages. * The {@link ProtonSession} access this resource atomically. */ private static final class Resource { private static final Resource EMPTY = new Resource(); private static final Resource DISPOSED = new Resource(); private final Session session; /** * Creates a Resource initialized with a QPid Proton-j {@link Session}. * * @param session the session. */ Resource(Session session) { this.session = Objects.requireNonNull(session, "'session' cannot be null."); } /** * Gets the underlying QPid Proton-j {@link Session}. * * @return the session. */ Session value() { assert this != EMPTY; return this.session; } /** * Check that if resource is in a valid state i.e., if it holds a session. An error is thrown if the resource * is not initialized with a session or disposed. * * @param logger the logger to log the error in case of invalid state. * @param endpointType the type of the endpoint (e.g., sender, receiver, channel) that the call site want to * host on the underlying session. The provided string value is used only to form error message. * @throws IllegalStateException if the resource is not initialized with a session. * @throws ProtonSessionClosedException if the resource is disposed. */ void validate(ClientLogger logger, String endpointType) { if (this == Resource.EMPTY) { throw logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (this == Resource.DISPOSED) { throw logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, endpointType))); } } /** * Constructor for the static EMPTY and DISPOSED state. */ private Resource() { this.session = null; } } }
nit: i try to put all same named methods and overloads together so I know what options are there. I think the other evict method is up there.
private void evict(ReactorSession session, String message, Throwable error) { if (isOwnerDisposed.get()) { return; } final String name = session.getSessionName(); if (error != null) { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).log(message, error); } else { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).log(message); } evict(name); }
if (isOwnerDisposed.get()) {
private void evict(ReactorSession session, String message, Throwable error) { if (isOwnerDisposed.get()) { return; } final String name = session.getSessionName(); final String id = session.getId(); if (error != null) { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).addKeyValue(SESSION_ID_KEY, id).log(message, error); } else { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).addKeyValue(SESSION_ID_KEY, id).log(message); } evict(name); }
class ReactorSessionCache { private final ConcurrentMap<String, Entry> entries = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String connectionId; private final ReactorHandlerProvider handlerProvider; private final ReactorProvider reactorProvider; private final Duration openTimeout; private final AtomicBoolean isOwnerDisposed; private final ClientLogger logger; /** * Creates the cache. * * @param connectionId the id of the {@link ReactorConnection} owning the cache. * @param fullyQualifiedNamespace the host name of the broker that the owner is connected to. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher to dispatch work to QPid Reactor thread. * @param openTimeout the session open timeout. * @param logger the client logger. */ ReactorSessionCache(String connectionId, String fullyQualifiedNamespace, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, Duration openTimeout, ClientLogger logger) { this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.connectionId = connectionId; this.handlerProvider = handlerProvider; this.reactorProvider = reactorProvider; this.openTimeout = openTimeout; this.isOwnerDisposed = new AtomicBoolean(false); this.logger = logger; } /** * Obtain the session with the given name from the cache, first loading and opening the session if necessary. * <p> * The session returned from the cache will be already connected to the broker and ready to use. * </p> * <p> * A session will be evicted from the cache if it terminates (e.g., broker disconnected the session). * </p> * * @param connectionMono the Mono that emits QPid Proton-j {@link Connection} that host the session. * @param name the session name. * @param loader to load the session on cache miss, cache miss can happen if session is requested * for the first time or previously loaded one was evicted. * * @return the session, that is active and connected to the broker. */ Mono<ReactorSession> getOrLoad(Mono<Connection> connectionMono, String name, Loader loader) { final Mono<Entry> entryMono = connectionMono.map(connection -> { return entries.computeIfAbsent(name, sessionName -> { final ReactorSession session = load(connection, sessionName, loader); final Disposable disposable = setupAutoEviction(session); return new Entry(session, disposable); }); }); return entryMono.flatMap(entry -> { final ReactorSession session = entry.getSession(); return session.open() .doOnError(error -> evict(session, "Evicting failed to open or in-active session.", error)); }); } /** * Evicts the session from the cache. * * @param name the name of the session to evict. * @return true if the session was evicted, false if no session found with the given name. */ boolean evict(String name) { if (name == null) { return false; } final Entry removed = entries.remove(name); if (removed != null) { removed.dispose(); } return removed != null; } /** * Signal that the owner ({@link ReactorConnection}) of the cache is disposed of. */ void setOwnerDisposed() { isOwnerDisposed.set(true); } /** * When the owner {@link ReactorConnection} is being disposed of, all {@link ReactorSession} loaded into the cache * will receive shutdown signal through the channel established at ReactorSession's construction time, the owner * may use this method to waits for sessions to complete it closing. * * @return a Mono that completes when all sessions are closed via owner shutdown signaling. */ Mono<Void> awaitClose() { final ArrayList<Mono<Void>> closing = new ArrayList<>(entries.size()); for (Entry entry : entries.values()) { closing.add(entry.awaitSessionClose()); } return Mono.when(closing); } /** * Load a new {@link ReactorSession} to be cached. * * @param connection the QPid Proton-j connection to host the session. * @param name the session name. * @param loader the function to load the session. * * @return the session to cache. */ private ReactorSession load(Connection connection, String name, Loader loader) { final ProtonSession protonSession = new ProtonSession(connectionId, fullyQualifiedNamespace, connection, handlerProvider, reactorProvider, name, openTimeout, logger); return loader.load(new ProtonSessionWrapper(protonSession)); } /** * Register to evict the session from the cache when the session terminates. * * @param session the session to register for cache eviction. * @return the registration disposable. */ private Disposable setupAutoEviction(ReactorSession session) { return session.getEndpointStates().subscribe(__ -> { }, error -> { evict(session, "Evicting session terminated with error.", error); }, () -> { evict(session, "Evicting terminated session.", null); }); } /** * Attempt to evict the session from the cache. * * @param session the session to evict. * @param message the message to log on eviction. * @param error the error triggered the eviction. */ /** * Type to load a {@link ReactorSession} for caching it. */ @FunctionalInterface interface Loader { /** * Load a {@link ReactorSession} for caching. * * @param protonSession the {@link ProtonSession} to back the loaded {@link ReactorSession}. * <p> * TODO (anu): When removing v1, update signature to use 'ProtonSession' instead of wrapper. * </p> * * @return the session to cache. */ ReactorSession load(ProtonSessionWrapper protonSession); } /** * An entry in the cache holding {@link ReactorSession} and {@link Disposable} for the task to evict the entry * from the cache. */ private static final class Entry extends AtomicBoolean { private final ReactorSession session; private final Disposable disposable; /** * Creates a cache entry. * * @param session the session to cache. * @param disposable the disposable to evict the session from the cache. */ private Entry(ReactorSession session, Disposable disposable) { super(false); this.session = session; this.disposable = disposable; } /** * Gets the session cached in the entry. * * @return the session. */ private ReactorSession getSession() { return session; } /** * Await for the cached session to close. * * @return a Mono that completes when the session is closed. */ private Mono<Void> awaitSessionClose() { return session.isClosed(); } /** * Dispose of the cached session and the eviction disposable. */ private void dispose() { if (super.getAndSet(true)) { return; } session.closeAsync("closing session.", null, true).subscribe(); disposable.dispose(); } } }
class ReactorSessionCache { private final ConcurrentMap<String, Entry> entries = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String connectionId; private final ReactorHandlerProvider handlerProvider; private final ReactorProvider reactorProvider; private final Duration openTimeout; private final AtomicBoolean isOwnerDisposed; private final ClientLogger logger; /** * Creates the cache. * * @param connectionId the id of the {@link ReactorConnection} owning the cache. * @param fullyQualifiedNamespace the host name of the broker that the owner is connected to. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher to dispatch work to QPid Reactor thread. * @param openTimeout the session open timeout. * @param logger the client logger. */ ReactorSessionCache(String connectionId, String fullyQualifiedNamespace, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, Duration openTimeout, ClientLogger logger) { this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.connectionId = connectionId; this.handlerProvider = handlerProvider; this.reactorProvider = reactorProvider; this.openTimeout = openTimeout; this.isOwnerDisposed = new AtomicBoolean(false); this.logger = logger; } /** * Obtain the session with the given name from the cache, first loading and opening the session if necessary. * <p> * The session returned from the cache will be already connected to the broker and ready to use. * </p> * <p> * A session will be evicted from the cache if it terminates (e.g., broker disconnected the session). * </p> * * @param connectionMono the Mono that emits QPid Proton-j {@link Connection} that host the session. * @param name the session name. * @param loader to load the session on cache miss, cache miss can happen if session is requested * for the first time or previously loaded one was evicted. * * @return the session, that is active and connected to the broker. */ Mono<ReactorSession> getOrLoad(Mono<Connection> connectionMono, String name, Loader loader) { final Mono<Entry> entryMono = connectionMono.map(connection -> { return entries.computeIfAbsent(name, sessionName -> { final ReactorSession session = load(connection, sessionName, loader); final Disposable disposable = setupAutoEviction(session); return new Entry(session, disposable); }); }); return entryMono.flatMap(entry -> { final ReactorSession session = entry.getSession(); return session.open() .doOnError(error -> evict(session, "Evicting failed to open or in-active session.", error)); }); } /** * Evicts the session from the cache. * * @param name the name of the session to evict. * @return true if the session was evicted, false if no session found with the given name. */ boolean evict(String name) { if (name == null) { return false; } final Entry removed = entries.remove(name); if (removed != null) { removed.dispose(); } return removed != null; } /** * Signal that the owner ({@link ReactorConnection}) of the cache is disposed of. */ void setOwnerDisposed() { isOwnerDisposed.set(true); } /** * When the owner {@link ReactorConnection} is being disposed of, all {@link ReactorSession} loaded into the cache * will receive shutdown signal through the channel established at ReactorSession's construction time, the owner * may use this method to waits for sessions to complete it closing. * * @return a Mono that completes when all sessions are closed via owner shutdown signaling. */ Mono<Void> awaitClose() { final ArrayList<Mono<Void>> closing = new ArrayList<>(entries.size()); for (Entry entry : entries.values()) { closing.add(entry.awaitSessionClose()); } return Mono.when(closing); } /** * Load a new {@link ReactorSession} to be cached. * * @param connection the QPid Proton-j connection to host the session. * @param name the session name. * @param loader the function to load the session. * * @return the session to cache. */ private ReactorSession load(Connection connection, String name, Loader loader) { final ProtonSession protonSession = new ProtonSession(connectionId, fullyQualifiedNamespace, connection, handlerProvider, reactorProvider, name, openTimeout, logger); return loader.load(new ProtonSessionWrapper(protonSession)); } /** * Register to evict the session from the cache when the session terminates. * * @param session the session to register for cache eviction. * @return the registration disposable. */ private Disposable setupAutoEviction(ReactorSession session) { return session.getEndpointStates().subscribe(__ -> { }, error -> { evict(session, "Evicting session terminated with error.", error); }, () -> { evict(session, "Evicting terminated session.", null); }); } /** * Attempt to evict the session from the cache. * * @param session the session to evict. * @param message the message to log on eviction. * @param error the error triggered the eviction. */ /** * Type to load a {@link ReactorSession} for caching it. */ @FunctionalInterface interface Loader { /** * Load a {@link ReactorSession} for caching. * * @param protonSession the {@link ProtonSession} to back the loaded {@link ReactorSession}. * <p> * TODO (anu): When removing v1, update signature to use 'ProtonSession' instead of wrapper. * </p> * * @return the session to cache. */ ReactorSession load(ProtonSessionWrapper protonSession); } /** * An entry in the cache holding {@link ReactorSession} and {@link Disposable} for the task to evict the entry * from the cache. */ private static final class Entry extends AtomicBoolean { private final ReactorSession session; private final Disposable disposable; /** * Creates a cache entry. * * @param session the session to cache. * @param disposable the disposable to evict the session from the cache. */ private Entry(ReactorSession session, Disposable disposable) { super(false); this.session = session; this.disposable = disposable; } /** * Gets the session cached in the entry. * * @return the session. */ private ReactorSession getSession() { return session; } /** * Await for the cached session to close. * * @return a Mono that completes when the session is closed. */ private Mono<Void> awaitSessionClose() { return session.isClosed(); } /** * Dispose of the cached session and the eviction disposable. */ private void dispose() { if (super.getAndSet(true)) { return; } session.closeAsync("closing session.", null, true).subscribe(); disposable.dispose(); } } }
the reason for picking this current order was – the other _evict_ is package private and this one is private. So, I was grouping methods based on visibility, typically we follow such ordering for member methods, variables (like public -> package private -> private)
private void evict(ReactorSession session, String message, Throwable error) { if (isOwnerDisposed.get()) { return; } final String name = session.getSessionName(); if (error != null) { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).log(message, error); } else { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).log(message); } evict(name); }
if (isOwnerDisposed.get()) {
private void evict(ReactorSession session, String message, Throwable error) { if (isOwnerDisposed.get()) { return; } final String name = session.getSessionName(); final String id = session.getId(); if (error != null) { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).addKeyValue(SESSION_ID_KEY, id).log(message, error); } else { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).addKeyValue(SESSION_ID_KEY, id).log(message); } evict(name); }
class ReactorSessionCache { private final ConcurrentMap<String, Entry> entries = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String connectionId; private final ReactorHandlerProvider handlerProvider; private final ReactorProvider reactorProvider; private final Duration openTimeout; private final AtomicBoolean isOwnerDisposed; private final ClientLogger logger; /** * Creates the cache. * * @param connectionId the id of the {@link ReactorConnection} owning the cache. * @param fullyQualifiedNamespace the host name of the broker that the owner is connected to. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher to dispatch work to QPid Reactor thread. * @param openTimeout the session open timeout. * @param logger the client logger. */ ReactorSessionCache(String connectionId, String fullyQualifiedNamespace, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, Duration openTimeout, ClientLogger logger) { this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.connectionId = connectionId; this.handlerProvider = handlerProvider; this.reactorProvider = reactorProvider; this.openTimeout = openTimeout; this.isOwnerDisposed = new AtomicBoolean(false); this.logger = logger; } /** * Obtain the session with the given name from the cache, first loading and opening the session if necessary. * <p> * The session returned from the cache will be already connected to the broker and ready to use. * </p> * <p> * A session will be evicted from the cache if it terminates (e.g., broker disconnected the session). * </p> * * @param connectionMono the Mono that emits QPid Proton-j {@link Connection} that host the session. * @param name the session name. * @param loader to load the session on cache miss, cache miss can happen if session is requested * for the first time or previously loaded one was evicted. * * @return the session, that is active and connected to the broker. */ Mono<ReactorSession> getOrLoad(Mono<Connection> connectionMono, String name, Loader loader) { final Mono<Entry> entryMono = connectionMono.map(connection -> { return entries.computeIfAbsent(name, sessionName -> { final ReactorSession session = load(connection, sessionName, loader); final Disposable disposable = setupAutoEviction(session); return new Entry(session, disposable); }); }); return entryMono.flatMap(entry -> { final ReactorSession session = entry.getSession(); return session.open() .doOnError(error -> evict(session, "Evicting failed to open or in-active session.", error)); }); } /** * Evicts the session from the cache. * * @param name the name of the session to evict. * @return true if the session was evicted, false if no session found with the given name. */ boolean evict(String name) { if (name == null) { return false; } final Entry removed = entries.remove(name); if (removed != null) { removed.dispose(); } return removed != null; } /** * Signal that the owner ({@link ReactorConnection}) of the cache is disposed of. */ void setOwnerDisposed() { isOwnerDisposed.set(true); } /** * When the owner {@link ReactorConnection} is being disposed of, all {@link ReactorSession} loaded into the cache * will receive shutdown signal through the channel established at ReactorSession's construction time, the owner * may use this method to waits for sessions to complete it closing. * * @return a Mono that completes when all sessions are closed via owner shutdown signaling. */ Mono<Void> awaitClose() { final ArrayList<Mono<Void>> closing = new ArrayList<>(entries.size()); for (Entry entry : entries.values()) { closing.add(entry.awaitSessionClose()); } return Mono.when(closing); } /** * Load a new {@link ReactorSession} to be cached. * * @param connection the QPid Proton-j connection to host the session. * @param name the session name. * @param loader the function to load the session. * * @return the session to cache. */ private ReactorSession load(Connection connection, String name, Loader loader) { final ProtonSession protonSession = new ProtonSession(connectionId, fullyQualifiedNamespace, connection, handlerProvider, reactorProvider, name, openTimeout, logger); return loader.load(new ProtonSessionWrapper(protonSession)); } /** * Register to evict the session from the cache when the session terminates. * * @param session the session to register for cache eviction. * @return the registration disposable. */ private Disposable setupAutoEviction(ReactorSession session) { return session.getEndpointStates().subscribe(__ -> { }, error -> { evict(session, "Evicting session terminated with error.", error); }, () -> { evict(session, "Evicting terminated session.", null); }); } /** * Attempt to evict the session from the cache. * * @param session the session to evict. * @param message the message to log on eviction. * @param error the error triggered the eviction. */ /** * Type to load a {@link ReactorSession} for caching it. */ @FunctionalInterface interface Loader { /** * Load a {@link ReactorSession} for caching. * * @param protonSession the {@link ProtonSession} to back the loaded {@link ReactorSession}. * <p> * TODO (anu): When removing v1, update signature to use 'ProtonSession' instead of wrapper. * </p> * * @return the session to cache. */ ReactorSession load(ProtonSessionWrapper protonSession); } /** * An entry in the cache holding {@link ReactorSession} and {@link Disposable} for the task to evict the entry * from the cache. */ private static final class Entry extends AtomicBoolean { private final ReactorSession session; private final Disposable disposable; /** * Creates a cache entry. * * @param session the session to cache. * @param disposable the disposable to evict the session from the cache. */ private Entry(ReactorSession session, Disposable disposable) { super(false); this.session = session; this.disposable = disposable; } /** * Gets the session cached in the entry. * * @return the session. */ private ReactorSession getSession() { return session; } /** * Await for the cached session to close. * * @return a Mono that completes when the session is closed. */ private Mono<Void> awaitSessionClose() { return session.isClosed(); } /** * Dispose of the cached session and the eviction disposable. */ private void dispose() { if (super.getAndSet(true)) { return; } session.closeAsync("closing session.", null, true).subscribe(); disposable.dispose(); } } }
class ReactorSessionCache { private final ConcurrentMap<String, Entry> entries = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String connectionId; private final ReactorHandlerProvider handlerProvider; private final ReactorProvider reactorProvider; private final Duration openTimeout; private final AtomicBoolean isOwnerDisposed; private final ClientLogger logger; /** * Creates the cache. * * @param connectionId the id of the {@link ReactorConnection} owning the cache. * @param fullyQualifiedNamespace the host name of the broker that the owner is connected to. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher to dispatch work to QPid Reactor thread. * @param openTimeout the session open timeout. * @param logger the client logger. */ ReactorSessionCache(String connectionId, String fullyQualifiedNamespace, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, Duration openTimeout, ClientLogger logger) { this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.connectionId = connectionId; this.handlerProvider = handlerProvider; this.reactorProvider = reactorProvider; this.openTimeout = openTimeout; this.isOwnerDisposed = new AtomicBoolean(false); this.logger = logger; } /** * Obtain the session with the given name from the cache, first loading and opening the session if necessary. * <p> * The session returned from the cache will be already connected to the broker and ready to use. * </p> * <p> * A session will be evicted from the cache if it terminates (e.g., broker disconnected the session). * </p> * * @param connectionMono the Mono that emits QPid Proton-j {@link Connection} that host the session. * @param name the session name. * @param loader to load the session on cache miss, cache miss can happen if session is requested * for the first time or previously loaded one was evicted. * * @return the session, that is active and connected to the broker. */ Mono<ReactorSession> getOrLoad(Mono<Connection> connectionMono, String name, Loader loader) { final Mono<Entry> entryMono = connectionMono.map(connection -> { return entries.computeIfAbsent(name, sessionName -> { final ReactorSession session = load(connection, sessionName, loader); final Disposable disposable = setupAutoEviction(session); return new Entry(session, disposable); }); }); return entryMono.flatMap(entry -> { final ReactorSession session = entry.getSession(); return session.open() .doOnError(error -> evict(session, "Evicting failed to open or in-active session.", error)); }); } /** * Evicts the session from the cache. * * @param name the name of the session to evict. * @return true if the session was evicted, false if no session found with the given name. */ boolean evict(String name) { if (name == null) { return false; } final Entry removed = entries.remove(name); if (removed != null) { removed.dispose(); } return removed != null; } /** * Signal that the owner ({@link ReactorConnection}) of the cache is disposed of. */ void setOwnerDisposed() { isOwnerDisposed.set(true); } /** * When the owner {@link ReactorConnection} is being disposed of, all {@link ReactorSession} loaded into the cache * will receive shutdown signal through the channel established at ReactorSession's construction time, the owner * may use this method to waits for sessions to complete it closing. * * @return a Mono that completes when all sessions are closed via owner shutdown signaling. */ Mono<Void> awaitClose() { final ArrayList<Mono<Void>> closing = new ArrayList<>(entries.size()); for (Entry entry : entries.values()) { closing.add(entry.awaitSessionClose()); } return Mono.when(closing); } /** * Load a new {@link ReactorSession} to be cached. * * @param connection the QPid Proton-j connection to host the session. * @param name the session name. * @param loader the function to load the session. * * @return the session to cache. */ private ReactorSession load(Connection connection, String name, Loader loader) { final ProtonSession protonSession = new ProtonSession(connectionId, fullyQualifiedNamespace, connection, handlerProvider, reactorProvider, name, openTimeout, logger); return loader.load(new ProtonSessionWrapper(protonSession)); } /** * Register to evict the session from the cache when the session terminates. * * @param session the session to register for cache eviction. * @return the registration disposable. */ private Disposable setupAutoEviction(ReactorSession session) { return session.getEndpointStates().subscribe(__ -> { }, error -> { evict(session, "Evicting session terminated with error.", error); }, () -> { evict(session, "Evicting terminated session.", null); }); } /** * Attempt to evict the session from the cache. * * @param session the session to evict. * @param message the message to log on eviction. * @param error the error triggered the eviction. */ /** * Type to load a {@link ReactorSession} for caching it. */ @FunctionalInterface interface Loader { /** * Load a {@link ReactorSession} for caching. * * @param protonSession the {@link ProtonSession} to back the loaded {@link ReactorSession}. * <p> * TODO (anu): When removing v1, update signature to use 'ProtonSession' instead of wrapper. * </p> * * @return the session to cache. */ ReactorSession load(ProtonSessionWrapper protonSession); } /** * An entry in the cache holding {@link ReactorSession} and {@link Disposable} for the task to evict the entry * from the cache. */ private static final class Entry extends AtomicBoolean { private final ReactorSession session; private final Disposable disposable; /** * Creates a cache entry. * * @param session the session to cache. * @param disposable the disposable to evict the session from the cache. */ private Entry(ReactorSession session, Disposable disposable) { super(false); this.session = session; this.disposable = disposable; } /** * Gets the session cached in the entry. * * @return the session. */ private ReactorSession getSession() { return session; } /** * Await for the cached session to close. * * @return a Mono that completes when the session is closed. */ private Mono<Void> awaitSessionClose() { return session.isClosed(); } /** * Dispose of the cached session and the eviction disposable. */ private void dispose() { if (super.getAndSet(true)) { return; } session.closeAsync("closing session.", null, true).subscribe(); disposable.dispose(); } } }
reworked this type based on the feedback.
Mono<ProtonChannel> channel(final String name, Duration timeout) { final Mono<ProtonChannel> channel = Mono.create(sink -> { if (name == null) { sink.error(new NullPointerException("'name' cannot be null.")); return; } try { getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session; try { session = getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } final String senderName = name + ":sender"; final String receiverName = name + ":receiver"; sink.success(new ProtonChannel(name, session.sender(senderName), session.receiver(receiverName))); }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); sink.error(retriableAmqpError(null, message, e)); } else { sink.error(e); } } }); return channel.timeout(timeout, Mono.error(() -> { final String message = String.format(OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT, getConnectionId(), getName(), name); return retriableAmqpError(TIMEOUT_ERROR, message, null); })); }
getSession("channel");
Mono<ProtonChannel> channel(final String name, Duration timeout) { final Mono<ProtonChannel> channel = Mono.create(sink -> { if (name == null) { sink.error(new NullPointerException("'name' cannot be null.")); return; } try { resource.get().validate(logger, "channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session; try { session = getSession("channel"); } catch (ProtonSessionClosedException | IllegalStateException e) { sink.error(e); return; } final String senderName = name + ":sender"; final String receiverName = name + ":receiver"; sink.success(new ProtonChannel(name, session.sender(senderName), session.receiver(receiverName))); }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); sink.error(retriableAmqpError(null, message, e)); } else { sink.error(e); } } }); return channel.timeout(timeout, Mono.error(() -> { final String message = String.format(OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT, getConnectionId(), getName(), name); return retriableAmqpError(TIMEOUT_ERROR, message, null); })); }
class ProtonSession { private static final String SESSION_NOT_OPENED = "session has not been opened."; private static final String NOT_OPENING_DISPOSED_SESSION = "session is already disposed, not opening."; private static final String DISPOSED_MESSAGE_FORMAT = "Cannot create %s from a closed session."; private static final String REACTOR_CLOSED_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] connection-reactor is disposed."; private static final String OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] obtaining channel (%s) timed out."; private final AtomicReference<State> state = new AtomicReference<>(State.EMPTY); private final AtomicBoolean opened = new AtomicBoolean(false); private final Sinks.Empty<Void> openAwaiter = Sinks.empty(); private final Connection connection; private final ReactorProvider reactorProvider; private final SessionHandler handler; private final ClientLogger logger; /** * Creates a ProtonSession. * * @param connectionId the id of the QPid Proton-j Connection hosting the session. * @param hostname the host name of the broker that the QPid Proton-j Connection hosting * the session is connected to. * @param connection the QPid Proton-j Connection hosting the session. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher. * @param sessionName the session name. * @param openTimeout the session open timeout. * @param logger the client logger. */ ProtonSession(String connectionId, String hostname, Connection connection, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, String sessionName, Duration openTimeout, ClientLogger logger) { this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); Objects.requireNonNull(handlerProvider, "'handlerProvider' cannot be null."); this.handler = handlerProvider.createSessionHandler(connectionId, hostname, sessionName, openTimeout); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); } /** * Gets the session name. * * @return the session name. */ String getName() { return handler.getSessionName(); } /** * Gets the identifier of the QPid Proton-j Connection hosting the session. * * @return the connection identifier. */ String getConnectionId() { return handler.getConnectionId(); } /** * Gets the host name of the broker that the QPid Proton-j Connection facilitating the session * is connected to. * * @return the hostname. */ String getHostname() { return handler.getHostname(); } /** * Gets the error context of the session. * * @return the error context. */ AmqpErrorContext getErrorContext() { return handler.getErrorContext(); } /** * Gets the connectivity states of the session. * * @return the session's connectivity states. */ Flux<EndpointState> getEndpointStates() { return handler.getEndpointStates(); } /** * Gets the reactor dispatcher provider associated with the session. * <p> * Any operation (e.g., obtaining sender, receiver) on the session must be invoked on the reactor dispatcher. * </p> * * @return the reactor dispatcher provider. */ ReactorProvider getReactorProvider() { return reactorProvider; } /** * Opens the session in the QPid Proton-j Connection. * <p> * The session open attempt is made upon the first subscription, once opened later subscriptions will complete * immediately, i.e. there is an open-only-once semantics. * </p> * <p> * If the session (or parent Qpid Proton-j connection) is disposed after opening, any later operation attempts * (e.g., creating sender, receiver, channel) will fail. * </p> * <p> * By design, no re-open attempt will be made within this type. Lifetime of a {@link ProtonSession} instance is * scoped to life time of one low level Qpid Proton-j session instance it manages, which is scoped within the * life time of qpid Proton-j Connection hosting it. Re-establishing session requires querying the connection-cache * to obtain the latest connection (may not be same as the connection facilitated this session) then hosting and * opening a new {@link ProtonSession} on it. It means, upon a retriable {@link AmqpException} from any APIs (to * create sender, receiver, channel) in this type, the call sites needs to obtain a new {@link ProtonSession} * by polling the connection-cache. * </p> * * @return a mono that completes once the session is opened. * <p> * <ul>the mono can terminates with retriable {@link AmqpException} if * <li>the session disposal happened while opening,</li> * <li>or the connection reactor thread got shutdown while opening.</li> * </ul> * </p> */ Mono<Void> open() { if (opened.getAndSet(true)) { return openAwaiter.asMono(); } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session = connection.session(); BaseHandler.setHandler(session, handler); session.open(); logger.atInfo() .addKeyValue(SESSION_NAME_KEY, handler.getSessionName()) .log("session local open scheduled."); if (state.compareAndSet(State.EMPTY, new State(session))) { openAwaiter.emitEmpty(FAIL_FAST); } else { session.close(); if (state.get() == State.DISPOSED) { openAwaiter.emitError(new ProtonSessionClosedException(NOT_OPENING_DISPOSED_SESSION), FAIL_FAST); } else { openAwaiter.emitError(new IllegalStateException("session is already opened."), FAIL_FAST); } } }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); openAwaiter.emitError(retriableAmqpError(null, message, e), FAIL_FAST); } else { openAwaiter.emitError(e, FAIL_FAST); } } return openAwaiter.asMono(); } /** * Gets a bidirectional channel on the session. * <p> * A channel consists of a sender link and a receiver link, and is used for management operations where a sender * link is used to send a request to the broker and a receiver link gets the associated response from the broker. * </p> * * @param name the channel name, which is used as the name prefix for sender link and receiver link in the channel. * @param timeout the timeout for obtaining the channel. * * @return a mono that completes with a {@link ProtonChannel} once the channel is created in the session. * <p> * <ul> * <li>the mono terminates with {@link IllegalStateException} if the session is not opened yet via {@link * <li>the mono terminates with * <ul> * <li>a retriable {@link ProtonSessionClosedException} if the session is disposed,</li> * <li>a retriable {@link AmqpException} if obtaining channel timeout,</li> * <li>or a retriable {@link AmqpException} if the connection reactor thread is shutdown.</li> * </ul> * </li> * </ul> * </p> */ /** * Gets a QPid Proton-j sender on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the sender was made before opening the session. * @throws ProtonSessionClosedException (a retriable {@link AmqpException}) if the session was disposed. */ Sender senderUnsafe(String name) { final Session session = getSession("sender link"); return session.sender(name); } /** * Gets a QPid Proton-j receiver on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the receiver was made before opening the session. * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ Receiver receiverUnsafe(String name) { final Session session = getSession("receive link"); return session.receiver(name); } /** * Begin the disposal by locally closing the underlying QPid Proton-j session. * * @param errorCondition the error condition to close the session with. */ void beginClose(ErrorCondition errorCondition) { final State s = state.getAndSet(State.DISPOSED); if (s == State.EMPTY || s == State.DISPOSED) { return; } final Session session = s.get(); if (session.getLocalState() != EndpointState.CLOSED) { session.close(); if (errorCondition != null && session.getCondition() == null) { session.setCondition(errorCondition); } } } /** * Completes the disposal by closing the {@link SessionHandler}. */ void endClose() { handler.close(); } /** * Obtain the underlying QPid Proton-j {@link Session} atomically. * * @param resourceType the type of the resource (e.g., sender, receiver, channel) that the call site want to host * on the obtained session. The provided string value is used only to form error message for any exception. * * @return the QPid Proton-j session. * @throws IllegalStateException if the attempt to obtain the session was made before opening via {@link * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ private Session getSession(String resourceType) { final State s = state.get(); if (s == State.EMPTY) { throw logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (s == State.DISPOSED) { throw logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, resourceType))); } return s.get(); } /** * Creates a retriable AMQP exception. * <p> * The call sites uses this method to translate a session unavailability "event" (session disposed, session operation * timed-out or connection being closed) to a retriable error. While the "event" is transient, recovering from it * by creating a new session on current connection or on a new connection needs to be done not by this class or * the parent 'ReactorConnection' owning this ProtonSession but by the downstream. E.g., the downstream Consumer, * Producer Client that has access to the chain to propagate retry request to top level V2 ReactorConnectionCache. * </p> * @param condition the error condition. * @param message the error message. * @param cause the actual cause of error. * @return the retriable AMQP exception. */ private AmqpException retriableAmqpError(AmqpErrorCondition condition, String message, Throwable cause) { return new AmqpException(true, condition, message, cause, handler.getErrorContext()); } /** * Type representing a bidirectional channel hosted on the QPid Proton-j session. * <p> * The {@link RequestResponseChannel} underneath uses an instance of {@link ProtonChannel} for the bi-directional * communication with the broker. * </p> */ static final class ProtonChannel { private final String name; private final Sender sender; private final Receiver receiver; /** * Creates a ProtonChannel. * * @param name the channel name. * @param sender the sender endpoint of the channel. * @param receiver the receiver endpoint of the channel. */ ProtonChannel(String name, Sender sender, Receiver receiver) { this.name = name; this.sender = sender; this.receiver = receiver; } /** * Gets the channel name. * * @return the channel name. */ String getName() { return name; } /** * Gets the sender endpoint of the channel. * * @return the channel's sender endpoint. */ Sender getSender() { return sender; } /** * Gets the receiver endpoint of the channel. * * @return the channel's receiver endpoint. */ Receiver getReceiver() { return receiver; } } /** * A retriable {@link AmqpException} indicating session is disposed. */ static final class ProtonSessionClosedException extends AmqpException { private ProtonSessionClosedException(String message) { super(true, message, null); } } /** * A type to atomically access the underlying QPid Proton-j {@link Session} that {@link ProtonSession} manages. */ private static final class State { private static final State EMPTY = new State(); private static final State DISPOSED = new State(); private final Session session; private State() { this.session = null; } private State(Session session) { this.session = Objects.requireNonNull(session, "'session' cannot be null."); } private Session get() { assert this != EMPTY; return this.session; } } }
class ProtonSession { private static final String SESSION_NOT_OPENED = "session has not been opened."; private static final String NOT_OPENING_DISPOSED_SESSION = "session is already disposed, not opening."; private static final String DISPOSED_MESSAGE_FORMAT = "Cannot create %s from a closed session."; private static final String REACTOR_CLOSED_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] connection-reactor is disposed."; private static final String OBTAIN_CHANNEL_TIMEOUT_MESSAGE_FORMAT = "connectionId:[%s] sessionName:[%s] obtaining channel (%s) timed out."; private final AtomicReference<Resource> resource = new AtomicReference<>(Resource.EMPTY); private final AtomicBoolean opened = new AtomicBoolean(false); private final Sinks.Empty<Void> openAwaiter = Sinks.empty(); private final Connection connection; private final ReactorProvider reactorProvider; private final SessionHandler handler; private final String id; private final ClientLogger logger; /** * Creates a ProtonSession. * * @param connectionId the id of the QPid Proton-j Connection hosting the session. * @param hostname the host name of the broker that the QPid Proton-j Connection hosting * the session is connected to. * @param connection the QPid Proton-j Connection hosting the session. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher. * @param sessionName the session name. * @param openTimeout the session open timeout. * @param logger the client logger. */ ProtonSession(String connectionId, String hostname, Connection connection, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, String sessionName, Duration openTimeout, ClientLogger logger) { this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); Objects.requireNonNull(handlerProvider, "'handlerProvider' cannot be null."); this.handler = handlerProvider.createSessionHandler(connectionId, hostname, sessionName, openTimeout); this.id = handler.getId(); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); } /** * Gets the id, useful for the logging purposes. * * @return the id. */ String getId() { return id; } /** * Gets the session name. * * @return the session name. */ String getName() { return handler.getSessionName(); } /** * Gets the identifier of the QPid Proton-j Connection hosting the session. * * @return the connection identifier. */ String getConnectionId() { return handler.getConnectionId(); } /** * Gets the host name of the broker that the QPid Proton-j Connection facilitating the session * is connected to. * * @return the hostname. */ String getHostname() { return handler.getHostname(); } /** * Gets the error context of the session. * * @return the error context. */ AmqpErrorContext getErrorContext() { return handler.getErrorContext(); } /** * Gets the connectivity states of the session. * * @return the session's connectivity states. */ Flux<EndpointState> getEndpointStates() { return handler.getEndpointStates(); } /** * Gets the reactor dispatcher provider associated with the session. * <p> * Any operation (e.g., obtaining sender, receiver) on the session must be invoked on the reactor dispatcher. * </p> * * @return the reactor dispatcher provider. */ ReactorProvider getReactorProvider() { return reactorProvider; } /** * Opens the session in the QPid Proton-j Connection. * <p> * The session open attempt is made upon the first subscription, once opened later subscriptions will complete * immediately, i.e. there is an open-only-once semantics. * </p> * <p> * If the session (or parent Qpid Proton-j connection) is disposed after opening, any later operation attempts * (e.g., creating sender, receiver, channel) will fail. * </p> * <p> * By design, no re-open attempt will be made within this type. Lifetime of a {@link ProtonSession} instance is * scoped to life time of one low level Qpid Proton-j session instance it manages, which is scoped within the * life time of qpid Proton-j Connection hosting it. Re-establishing session requires querying the connection-cache * to obtain the latest connection (may not be same as the connection facilitated this session) then hosting and * opening a new {@link ProtonSession} on it. It means, upon a retriable {@link AmqpException} from any APIs (to * create sender, receiver, channel) in this type, the call sites needs to obtain a new {@link ProtonSession} * by polling the connection-cache. * </p> * * @return a mono that completes once the session is opened. * <p> * <ul>the mono can terminates with retriable {@link AmqpException} if * <li>the session disposal happened while opening,</li> * <li>or the connection reactor thread got shutdown while opening.</li> * </ul> * </p> */ Mono<Void> open() { if (opened.getAndSet(true)) { return openAwaiter.asMono(); } try { getReactorProvider().getReactorDispatcher().invoke(() -> { final Session session = connection.session(); BaseHandler.setHandler(session, handler); session.open(); logger.atInfo() .addKeyValue(SESSION_NAME_KEY, handler.getSessionName()) .addKeyValue(SESSION_ID_KEY, id) .log("session local open scheduled."); if (resource.compareAndSet(Resource.EMPTY, new Resource(session))) { openAwaiter.emitEmpty(FAIL_FAST); } else { session.close(); if (resource.get() == Resource.DISPOSED) { openAwaiter.emitError(new ProtonSessionClosedException(NOT_OPENING_DISPOSED_SESSION), FAIL_FAST); } else { openAwaiter.emitError(new IllegalStateException("session is already opened."), FAIL_FAST); } } }); } catch (Exception e) { if (e instanceof IOException | e instanceof RejectedExecutionException) { final String message = String.format(REACTOR_CLOSED_MESSAGE_FORMAT, getConnectionId(), getName()); openAwaiter.emitError(retriableAmqpError(null, message, e), FAIL_FAST); } else { openAwaiter.emitError(e, FAIL_FAST); } } return openAwaiter.asMono(); } /** * Gets a bidirectional channel on the session. * <p> * A channel consists of a sender link and a receiver link, and is used for management operations where a sender * link is used to send a request to the broker and a receiver link gets the associated response from the broker. * </p> * * @param name the channel name, which is used as the name prefix for sender link and receiver link in the channel. * @param timeout the timeout for obtaining the channel. * * @return a mono that completes with a {@link ProtonChannel} once the channel is created in the session. * <p> * <ul> * <li>the mono terminates with {@link IllegalStateException} if the session is not opened yet via {@link * <li>the mono terminates with * <ul> * <li>a retriable {@link ProtonSessionClosedException} if the session is disposed,</li> * <li>a retriable {@link AmqpException} if obtaining channel timeout,</li> * <li>or a retriable {@link AmqpException} if the connection reactor thread is shutdown.</li> * </ul> * </li> * </ul> * </p> */ /** * Gets a QPid Proton-j sender on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the sender was made before opening the session. * @throws ProtonSessionClosedException (a retriable {@link AmqpException}) if the session was disposed. */ Sender senderUnsafe(String name) { final Session session = getSession("sender link"); return session.sender(name); } /** * Gets a QPid Proton-j receiver on the session. * <p> * The call site required to invoke this method on Reactor dispatcher thread using {@link * It is possible to run into race conditions with QPid Proton-j if invoked from any other threads. * </p> * * @param name the sender name. * * @return the sender. * @throws IllegalStateException if the attempt to obtain the receiver was made before opening the session. * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ Receiver receiverUnsafe(String name) { final Session session = getSession("receive link"); return session.receiver(name); } /** * Begin the disposal by locally closing the underlying QPid Proton-j session. * * @param errorCondition the error condition to close the session with. */ void beginClose(ErrorCondition errorCondition) { final Resource s = resource.getAndSet(Resource.DISPOSED); if (s == Resource.EMPTY || s == Resource.DISPOSED) { return; } final Session session = s.value(); if (session.getLocalState() != EndpointState.CLOSED) { session.close(); if (errorCondition != null && session.getCondition() == null) { session.setCondition(errorCondition); } } } /** * Completes the disposal by closing the {@link SessionHandler}. */ void endClose() { handler.close(); } /** * Obtain the underlying QPid Proton-j {@link Session} atomically. * * @param endpointType the type of the endpoint (e.g., sender, receiver, channel) that the call site want to host * on the obtained session. The provided string value is used only to form error message for any exception. * * @return the QPid Proton-j session. * @throws IllegalStateException if the attempt to obtain the session was made before opening via {@link * @throws ProtonSessionClosedException a retriable {@link AmqpException}) if the session was disposed. */ private Session getSession(String endpointType) { final Resource r = resource.get(); r.validate(logger, endpointType); return r.value(); } /** * Creates a retriable AMQP exception. * <p> * The call sites uses this method to translate a session unavailability "event" (session disposed, session operation * timed-out or connection being closed) to a retriable error. While the "event" is transient, recovering from it * by creating a new session on current connection or on a new connection needs to be done not by this class or * the parent 'ReactorConnection' owning this ProtonSession but by the downstream. E.g., the downstream Consumer, * Producer Client that has access to the chain to propagate retry request to top level V2 ReactorConnectionCache. * </p> * @param condition the error condition. * @param message the error message. * @param cause the actual cause of error. * @return the retriable AMQP exception. */ private AmqpException retriableAmqpError(AmqpErrorCondition condition, String message, Throwable cause) { return new AmqpException(true, condition, message, cause, handler.getErrorContext()); } /** * Type representing a bidirectional channel hosted on the QPid Proton-j session. * <p> * The {@link RequestResponseChannel} underneath uses an instance of {@link ProtonChannel} for the bi-directional * communication with the broker. * </p> */ static final class ProtonChannel { private final String name; private final Sender sender; private final Receiver receiver; /** * Creates a ProtonChannel. * * @param name the channel name. * @param sender the sender endpoint of the channel. * @param receiver the receiver endpoint of the channel. */ ProtonChannel(String name, Sender sender, Receiver receiver) { this.name = name; this.sender = sender; this.receiver = receiver; } /** * Gets the channel name. * * @return the channel name. */ String getName() { return name; } /** * Gets the sender endpoint of the channel. * * @return the channel's sender endpoint. */ Sender getSender() { return sender; } /** * Gets the receiver endpoint of the channel. * * @return the channel's receiver endpoint. */ Receiver getReceiver() { return receiver; } } /** * A retriable {@link AmqpException} indicating session is disposed. */ static final class ProtonSessionClosedException extends AmqpException { private ProtonSessionClosedException(String message) { super(true, message, null); } } /** * A type to store the underlying QPid Proton-j {@link Session} that the {@link ProtonSession} manages. * The {@link ProtonSession} access this resource atomically. */ private static final class Resource { private static final Resource EMPTY = new Resource(); private static final Resource DISPOSED = new Resource(); private final Session session; /** * Creates a Resource initialized with a QPid Proton-j {@link Session}. * * @param session the session. */ Resource(Session session) { this.session = Objects.requireNonNull(session, "'session' cannot be null."); } /** * Gets the underlying QPid Proton-j {@link Session}. * * @return the session. */ Session value() { assert this != EMPTY; return this.session; } /** * Check that if resource is in a valid state i.e., if it holds a session. An error is thrown if the resource * is not initialized with a session or disposed. * * @param logger the logger to log the error in case of invalid state. * @param endpointType the type of the endpoint (e.g., sender, receiver, channel) that the call site want to * host on the underlying session. The provided string value is used only to form error message. * @throws IllegalStateException if the resource is not initialized with a session. * @throws ProtonSessionClosedException if the resource is disposed. */ void validate(ClientLogger logger, String endpointType) { if (this == Resource.EMPTY) { throw logger.logExceptionAsError(new IllegalStateException(SESSION_NOT_OPENED)); } if (this == Resource.DISPOSED) { throw logger.logExceptionAsWarning( new ProtonSessionClosedException(String.format(DISPOSED_MESSAGE_FORMAT, endpointType))); } } /** * Constructor for the static EMPTY and DISPOSED state. */ private Resource() { this.session = null; } } }
resolving this based on the above comment. let me know if we need to revisit this.
private void evict(ReactorSession session, String message, Throwable error) { if (isOwnerDisposed.get()) { return; } final String name = session.getSessionName(); if (error != null) { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).log(message, error); } else { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).log(message); } evict(name); }
if (isOwnerDisposed.get()) {
private void evict(ReactorSession session, String message, Throwable error) { if (isOwnerDisposed.get()) { return; } final String name = session.getSessionName(); final String id = session.getId(); if (error != null) { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).addKeyValue(SESSION_ID_KEY, id).log(message, error); } else { logger.atInfo().addKeyValue(SESSION_NAME_KEY, name).addKeyValue(SESSION_ID_KEY, id).log(message); } evict(name); }
class ReactorSessionCache { private final ConcurrentMap<String, Entry> entries = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String connectionId; private final ReactorHandlerProvider handlerProvider; private final ReactorProvider reactorProvider; private final Duration openTimeout; private final AtomicBoolean isOwnerDisposed; private final ClientLogger logger; /** * Creates the cache. * * @param connectionId the id of the {@link ReactorConnection} owning the cache. * @param fullyQualifiedNamespace the host name of the broker that the owner is connected to. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher to dispatch work to QPid Reactor thread. * @param openTimeout the session open timeout. * @param logger the client logger. */ ReactorSessionCache(String connectionId, String fullyQualifiedNamespace, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, Duration openTimeout, ClientLogger logger) { this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.connectionId = connectionId; this.handlerProvider = handlerProvider; this.reactorProvider = reactorProvider; this.openTimeout = openTimeout; this.isOwnerDisposed = new AtomicBoolean(false); this.logger = logger; } /** * Obtain the session with the given name from the cache, first loading and opening the session if necessary. * <p> * The session returned from the cache will be already connected to the broker and ready to use. * </p> * <p> * A session will be evicted from the cache if it terminates (e.g., broker disconnected the session). * </p> * * @param connectionMono the Mono that emits QPid Proton-j {@link Connection} that host the session. * @param name the session name. * @param loader to load the session on cache miss, cache miss can happen if session is requested * for the first time or previously loaded one was evicted. * * @return the session, that is active and connected to the broker. */ Mono<ReactorSession> getOrLoad(Mono<Connection> connectionMono, String name, Loader loader) { final Mono<Entry> entryMono = connectionMono.map(connection -> { return entries.computeIfAbsent(name, sessionName -> { final ReactorSession session = load(connection, sessionName, loader); final Disposable disposable = setupAutoEviction(session); return new Entry(session, disposable); }); }); return entryMono.flatMap(entry -> { final ReactorSession session = entry.getSession(); return session.open() .doOnError(error -> evict(session, "Evicting failed to open or in-active session.", error)); }); } /** * Evicts the session from the cache. * * @param name the name of the session to evict. * @return true if the session was evicted, false if no session found with the given name. */ boolean evict(String name) { if (name == null) { return false; } final Entry removed = entries.remove(name); if (removed != null) { removed.dispose(); } return removed != null; } /** * Signal that the owner ({@link ReactorConnection}) of the cache is disposed of. */ void setOwnerDisposed() { isOwnerDisposed.set(true); } /** * When the owner {@link ReactorConnection} is being disposed of, all {@link ReactorSession} loaded into the cache * will receive shutdown signal through the channel established at ReactorSession's construction time, the owner * may use this method to waits for sessions to complete it closing. * * @return a Mono that completes when all sessions are closed via owner shutdown signaling. */ Mono<Void> awaitClose() { final ArrayList<Mono<Void>> closing = new ArrayList<>(entries.size()); for (Entry entry : entries.values()) { closing.add(entry.awaitSessionClose()); } return Mono.when(closing); } /** * Load a new {@link ReactorSession} to be cached. * * @param connection the QPid Proton-j connection to host the session. * @param name the session name. * @param loader the function to load the session. * * @return the session to cache. */ private ReactorSession load(Connection connection, String name, Loader loader) { final ProtonSession protonSession = new ProtonSession(connectionId, fullyQualifiedNamespace, connection, handlerProvider, reactorProvider, name, openTimeout, logger); return loader.load(new ProtonSessionWrapper(protonSession)); } /** * Register to evict the session from the cache when the session terminates. * * @param session the session to register for cache eviction. * @return the registration disposable. */ private Disposable setupAutoEviction(ReactorSession session) { return session.getEndpointStates().subscribe(__ -> { }, error -> { evict(session, "Evicting session terminated with error.", error); }, () -> { evict(session, "Evicting terminated session.", null); }); } /** * Attempt to evict the session from the cache. * * @param session the session to evict. * @param message the message to log on eviction. * @param error the error triggered the eviction. */ /** * Type to load a {@link ReactorSession} for caching it. */ @FunctionalInterface interface Loader { /** * Load a {@link ReactorSession} for caching. * * @param protonSession the {@link ProtonSession} to back the loaded {@link ReactorSession}. * <p> * TODO (anu): When removing v1, update signature to use 'ProtonSession' instead of wrapper. * </p> * * @return the session to cache. */ ReactorSession load(ProtonSessionWrapper protonSession); } /** * An entry in the cache holding {@link ReactorSession} and {@link Disposable} for the task to evict the entry * from the cache. */ private static final class Entry extends AtomicBoolean { private final ReactorSession session; private final Disposable disposable; /** * Creates a cache entry. * * @param session the session to cache. * @param disposable the disposable to evict the session from the cache. */ private Entry(ReactorSession session, Disposable disposable) { super(false); this.session = session; this.disposable = disposable; } /** * Gets the session cached in the entry. * * @return the session. */ private ReactorSession getSession() { return session; } /** * Await for the cached session to close. * * @return a Mono that completes when the session is closed. */ private Mono<Void> awaitSessionClose() { return session.isClosed(); } /** * Dispose of the cached session and the eviction disposable. */ private void dispose() { if (super.getAndSet(true)) { return; } session.closeAsync("closing session.", null, true).subscribe(); disposable.dispose(); } } }
class ReactorSessionCache { private final ConcurrentMap<String, Entry> entries = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String connectionId; private final ReactorHandlerProvider handlerProvider; private final ReactorProvider reactorProvider; private final Duration openTimeout; private final AtomicBoolean isOwnerDisposed; private final ClientLogger logger; /** * Creates the cache. * * @param connectionId the id of the {@link ReactorConnection} owning the cache. * @param fullyQualifiedNamespace the host name of the broker that the owner is connected to. * @param handlerProvider the handler provider for various type of endpoints (session, link). * @param reactorProvider the provider for reactor dispatcher to dispatch work to QPid Reactor thread. * @param openTimeout the session open timeout. * @param logger the client logger. */ ReactorSessionCache(String connectionId, String fullyQualifiedNamespace, ReactorHandlerProvider handlerProvider, ReactorProvider reactorProvider, Duration openTimeout, ClientLogger logger) { this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.connectionId = connectionId; this.handlerProvider = handlerProvider; this.reactorProvider = reactorProvider; this.openTimeout = openTimeout; this.isOwnerDisposed = new AtomicBoolean(false); this.logger = logger; } /** * Obtain the session with the given name from the cache, first loading and opening the session if necessary. * <p> * The session returned from the cache will be already connected to the broker and ready to use. * </p> * <p> * A session will be evicted from the cache if it terminates (e.g., broker disconnected the session). * </p> * * @param connectionMono the Mono that emits QPid Proton-j {@link Connection} that host the session. * @param name the session name. * @param loader to load the session on cache miss, cache miss can happen if session is requested * for the first time or previously loaded one was evicted. * * @return the session, that is active and connected to the broker. */ Mono<ReactorSession> getOrLoad(Mono<Connection> connectionMono, String name, Loader loader) { final Mono<Entry> entryMono = connectionMono.map(connection -> { return entries.computeIfAbsent(name, sessionName -> { final ReactorSession session = load(connection, sessionName, loader); final Disposable disposable = setupAutoEviction(session); return new Entry(session, disposable); }); }); return entryMono.flatMap(entry -> { final ReactorSession session = entry.getSession(); return session.open() .doOnError(error -> evict(session, "Evicting failed to open or in-active session.", error)); }); } /** * Evicts the session from the cache. * * @param name the name of the session to evict. * @return true if the session was evicted, false if no session found with the given name. */ boolean evict(String name) { if (name == null) { return false; } final Entry removed = entries.remove(name); if (removed != null) { removed.dispose(); } return removed != null; } /** * Signal that the owner ({@link ReactorConnection}) of the cache is disposed of. */ void setOwnerDisposed() { isOwnerDisposed.set(true); } /** * When the owner {@link ReactorConnection} is being disposed of, all {@link ReactorSession} loaded into the cache * will receive shutdown signal through the channel established at ReactorSession's construction time, the owner * may use this method to waits for sessions to complete it closing. * * @return a Mono that completes when all sessions are closed via owner shutdown signaling. */ Mono<Void> awaitClose() { final ArrayList<Mono<Void>> closing = new ArrayList<>(entries.size()); for (Entry entry : entries.values()) { closing.add(entry.awaitSessionClose()); } return Mono.when(closing); } /** * Load a new {@link ReactorSession} to be cached. * * @param connection the QPid Proton-j connection to host the session. * @param name the session name. * @param loader the function to load the session. * * @return the session to cache. */ private ReactorSession load(Connection connection, String name, Loader loader) { final ProtonSession protonSession = new ProtonSession(connectionId, fullyQualifiedNamespace, connection, handlerProvider, reactorProvider, name, openTimeout, logger); return loader.load(new ProtonSessionWrapper(protonSession)); } /** * Register to evict the session from the cache when the session terminates. * * @param session the session to register for cache eviction. * @return the registration disposable. */ private Disposable setupAutoEviction(ReactorSession session) { return session.getEndpointStates().subscribe(__ -> { }, error -> { evict(session, "Evicting session terminated with error.", error); }, () -> { evict(session, "Evicting terminated session.", null); }); } /** * Attempt to evict the session from the cache. * * @param session the session to evict. * @param message the message to log on eviction. * @param error the error triggered the eviction. */ /** * Type to load a {@link ReactorSession} for caching it. */ @FunctionalInterface interface Loader { /** * Load a {@link ReactorSession} for caching. * * @param protonSession the {@link ProtonSession} to back the loaded {@link ReactorSession}. * <p> * TODO (anu): When removing v1, update signature to use 'ProtonSession' instead of wrapper. * </p> * * @return the session to cache. */ ReactorSession load(ProtonSessionWrapper protonSession); } /** * An entry in the cache holding {@link ReactorSession} and {@link Disposable} for the task to evict the entry * from the cache. */ private static final class Entry extends AtomicBoolean { private final ReactorSession session; private final Disposable disposable; /** * Creates a cache entry. * * @param session the session to cache. * @param disposable the disposable to evict the session from the cache. */ private Entry(ReactorSession session, Disposable disposable) { super(false); this.session = session; this.disposable = disposable; } /** * Gets the session cached in the entry. * * @return the session. */ private ReactorSession getSession() { return session; } /** * Await for the cached session to close. * * @return a Mono that completes when the session is closed. */ private Mono<Void> awaitSessionClose() { return session.isClosed(); } /** * Dispose of the cached session and the eviction disposable. */ private void dispose() { if (super.getAndSet(true)) { return; } session.closeAsync("closing session.", null, true).subscribe(); disposable.dispose(); } } }
What's this? Isn't it same?
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
Fixed in the new version.
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
I mean, do we need to set the supportPlan for Free/Standard? What if we don't set that at all for Free/Standard? Or only set if it was not set (`null`)?
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
Yes, it need to set the supportPlan. The `LongTermSupport` and `Premium` tier should be enabled/disabled together. So when the sku is change from premium to free or standard, supportPlan must be updated to `official`. And I also verified through test cases that such combination restrictions do exist.
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
What do you mean? If the `sku=Free + supportPlan=AKSLONG_TERM_SUPPORT`, request will fail? This seems not same as I heard in yesterday's meeting? @XiaofeiCao
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
![image](https://github.com/Azure/azure-sdk-for-java/assets/74638143/e4b7e7de-dfa2-4626-a38e-bb5f042fa380)
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
paste me a log of your request JSON and response JSON, in fail case.
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
Default settings of Kubernetes Cluster: Sku: FREE SupportPlan: KUBERNETES_OFFICIA `kubernetesCluster.update().withFreeSku(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT).apply();` [test.log](https://github.com/Azure/azure-sdk-for-java/files/14519405/test.log) `kubernetesCluster.update().withStandardSku(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT).apply();` [test.log](https://github.com/Azure/azure-sdk-for-java/files/14519509/test.log)
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
OK. Then just delete the `if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) {`. If only `KUBERNETES_OFFICIAL` is allowed, having the condition does not make sense.
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
Strange. I wonder what [this](https://learn.microsoft.com/en-us/azure/aks/long-term-support#enable-long-term-support) means: <img width="852" alt="Screenshot 2024-03-07 at 2 46 35 PM" src="https://github.com/Azure/azure-sdk-for-java/assets/92354331/30c68c33-e7a0-4d10-910a-c52a1f3e3001"> If they are bound together, we can set them for the user I think.
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; }
}
public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); if (!KubernetesSupportPlan.KUBERNETES_OFFICIAL.equals(this.innerModel().supportPlan())) { this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); } return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
Extract method from line 656 to line 662 with a `computeFullPathLength(...)` method name?
private static String getHttpUrlFromServerSpanStableSemconv(Attributes attributes) { String scheme = attributes.get(SemanticAttributes.URL_SCHEME); if (scheme == null) { return null; } String host = attributes.get(SemanticAttributes.SERVER_ADDRESS); if (host == null) { return null; } Long port = attributes.get(SemanticAttributes.SERVER_PORT); String path = attributes.get(SemanticAttributes.URL_PATH); if (path == null) { return null; } String query = attributes.get(SemanticAttributes.URL_QUERY); int len = scheme.length() + host.length() + path.length(); if (port != null) { len += 6; } if (query != null) { len += query.length() + 1; } StringBuilder sb = new StringBuilder(len); sb.append(scheme); sb.append(": sb.append(host); if (port != null && port > 0) { sb.append(':'); sb.append(port); } sb.append(path); if (query != null) { sb.append('?'); sb.append(query); } return sb.toString(); }
}
private static String getHttpUrlFromServerSpanStableSemconv(Attributes attributes) { String scheme = attributes.get(SemanticAttributes.URL_SCHEME); if (scheme == null) { return null; } String host = attributes.get(SemanticAttributes.SERVER_ADDRESS); if (host == null) { return null; } Long port = attributes.get(SemanticAttributes.SERVER_PORT); String path = attributes.get(SemanticAttributes.URL_PATH); if (path == null) { return null; } String query = attributes.get(SemanticAttributes.URL_QUERY); int len = scheme.length() + host.length() + path.length(); if (port != null) { len += 6; } if (query != null) { len += query.length() + 1; } StringBuilder sb = new StringBuilder(len); sb.append(scheme); sb.append(": sb.append(host); if (port != null && port > 0 && !isDefaultPortForScheme(port, scheme)) { sb.append(':'); sb.append(port); } sb.append(path); if (query != null) { sb.append('?'); sb.append(query); } return sb.toString(); }
class SpanDataMapper { public static final String MS_PROCESSED_BY_METRIC_EXTRACTORS = "_MS.ProcessedByMetricExtractors"; private static final Set<String> SQL_DB_SYSTEMS = new HashSet<>( asList( SemanticAttributes.DbSystemValues.DB2, SemanticAttributes.DbSystemValues.DERBY, SemanticAttributes.DbSystemValues.MARIADB, SemanticAttributes.DbSystemValues.MSSQL, SemanticAttributes.DbSystemValues.MYSQL, SemanticAttributes.DbSystemValues.ORACLE, SemanticAttributes.DbSystemValues.POSTGRESQL, SemanticAttributes.DbSystemValues.SQLITE, SemanticAttributes.DbSystemValues.OTHER_SQL, SemanticAttributes.DbSystemValues.HSQLDB, SemanticAttributes.DbSystemValues.H2)); private static final String COSMOS = "Cosmos"; private static final Mappings MAPPINGS; private static final ContextTagKeys AI_DEVICE_OS = ContextTagKeys.fromString("ai.device.os"); static { MappingsBuilder mappingsBuilder = new MappingsBuilder(SPAN) .ignoreExact(AiSemanticAttributes.AZURE_SDK_NAMESPACE.getKey()) .ignoreExact(AiSemanticAttributes.AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey()) .ignoreExact(AiSemanticAttributes.AZURE_SDK_ENQUEUED_TIME.getKey()) .ignoreExact(AiSemanticAttributes.KAFKA_RECORD_QUEUE_TIME_MS.getKey()) .ignoreExact(AiSemanticAttributes.KAFKA_OFFSET.getKey()) .exact( SemanticAttributes.USER_AGENT_ORIGINAL.getKey(), (builder, value) -> { if (value instanceof String) { builder.addTag("ai.user.userAgent", (String) value); } }) .ignorePrefix("applicationinsights.internal.") .prefix( "http.request.header.", (telemetryBuilder, key, value) -> { if (value instanceof List) { telemetryBuilder.addProperty(key, Mappings.join((List<?>) value)); } }) .prefix( "http.response.header.", (telemetryBuilder, key, value) -> { if (value instanceof List) { telemetryBuilder.addProperty(key, Mappings.join((List<?>) value)); } }); applyCommonTags(mappingsBuilder); MAPPINGS = mappingsBuilder.build(); } private final boolean captureHttpServer4xxAsError; private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final BiPredicate<EventData, String> eventSuppressor; private final BiPredicate<SpanData, EventData> shouldSuppress; public SpanDataMapper( boolean captureHttpServer4xxAsError, BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, BiPredicate<EventData, String> eventSuppressor, BiPredicate<SpanData, EventData> shouldSuppress) { this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; this.telemetryInitializer = telemetryInitializer; this.eventSuppressor = eventSuppressor; this.shouldSuppress = shouldSuppress; } public TelemetryItem map(SpanData span) { Long itemCount = getItemCount(span); return map(span, itemCount); } public void map(SpanData span, Consumer<TelemetryItem> consumer) { Long itemCount = getItemCount(span); TelemetryItem telemetryItem = map(span, itemCount); consumer.accept(telemetryItem); exportEvents( span, telemetryItem.getTags().get(ContextTagKeys.AI_OPERATION_NAME.toString()), itemCount, consumer); } public TelemetryItem map(SpanData span, @Nullable Long itemCount) { if (RequestChecker.isRequest(span)) { return exportRequest(span, itemCount); } else { return exportRemoteDependency(span, span.getKind() == SpanKind.INTERNAL, itemCount); } } private static boolean checkIsPreAggregatedStandardMetric(SpanData span) { Boolean isPreAggregatedStandardMetric = span.getAttributes().get(AiSemanticAttributes.IS_PRE_AGGREGATED); return isPreAggregatedStandardMetric != null && isPreAggregatedStandardMetric; } private TelemetryItem exportRemoteDependency(SpanData span, boolean inProc, @Nullable Long itemCount) { RemoteDependencyTelemetryBuilder telemetryBuilder = RemoteDependencyTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationTags(telemetryBuilder, span); setTime(telemetryBuilder, span.getStartEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(span.getAttributes(), telemetryBuilder); addLinks(telemetryBuilder, span.getLinks()); telemetryBuilder.setId(span.getSpanId()); telemetryBuilder.setName(getDependencyName(span)); telemetryBuilder.setDuration( FormattedDuration.fromNanos(span.getEndEpochNanos() - span.getStartEpochNanos())); telemetryBuilder.setSuccess(getSuccess(span)); if (inProc) { telemetryBuilder.setType("InProc"); } else { applySemanticConventions(telemetryBuilder, span); } if (checkIsPreAggregatedStandardMetric(span)) { telemetryBuilder.addProperty(MS_PROCESSED_BY_METRIC_EXTRACTORS, "True"); } return telemetryBuilder.build(); } private static final Set<String> DEFAULT_HTTP_SPAN_NAMES = new HashSet<>( asList("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "PATCH")); private static String getDependencyName(SpanData span) { String name = span.getName(); String method = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.HTTP_REQUEST_METHOD, SemanticAttributes.HTTP_METHOD); if (method == null) { return name; } if (!DEFAULT_HTTP_SPAN_NAMES.contains(name)) { return name; } String url = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.URL_FULL, SemanticAttributes.HTTP_URL); if (url == null) { return name; } String path = UrlParser.getPath(url); if (path == null) { return name; } return path.isEmpty() ? method + " /" : method + " " + path; } private static void applySemanticConventions( RemoteDependencyTelemetryBuilder telemetryBuilder, SpanData span) { Attributes attributes = span.getAttributes(); String httpMethod = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_REQUEST_METHOD, SemanticAttributes.HTTP_METHOD); if (httpMethod != null) { applyHttpClientSpan(telemetryBuilder, attributes); return; } String rpcSystem = attributes.get(SemanticAttributes.RPC_SYSTEM); if (rpcSystem != null) { applyRpcClientSpan(telemetryBuilder, rpcSystem, attributes); return; } String dbSystem = attributes.get(SemanticAttributes.DB_SYSTEM); if (dbSystem == null) { dbSystem = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_TYPE); } if (dbSystem != null) { applyDatabaseClientSpan(telemetryBuilder, dbSystem, attributes); return; } String messagingSystem = getMessagingSystem(attributes); if (messagingSystem != null) { applyMessagingClientSpan(telemetryBuilder, span.getKind(), messagingSystem, attributes); return; } String target = getTargetOrDefault(attributes, Integer.MAX_VALUE, null); if (target != null) { telemetryBuilder.setTarget(target); return; } telemetryBuilder.setType("InProc"); } @Nullable private static String getMessagingSystem(Attributes attributes) { String azureNamespace = attributes.get(AiSemanticAttributes.AZURE_SDK_NAMESPACE); if (isAzureSdkMessaging(azureNamespace)) { return azureNamespace; } return attributes.get(SemanticAttributes.MESSAGING_SYSTEM); } private static void setOperationTags(AbstractTelemetryBuilder telemetryBuilder, SpanData span) { setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getParentSpanContext().getSpanId()); setOperationName(telemetryBuilder, span.getAttributes()); } private static void setOperationId(AbstractTelemetryBuilder telemetryBuilder, String traceId) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_ID.toString(), traceId); } private static void setOperationParentId( AbstractTelemetryBuilder telemetryBuilder, String parentSpanId) { if (SpanId.isValid(parentSpanId)) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId); } } private static void setOperationName( AbstractTelemetryBuilder telemetryBuilder, Attributes attributes) { String operationName = attributes.get(AiSemanticAttributes.OPERATION_NAME); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } } private static void setOperationName( AbstractTelemetryBuilder telemetryBuilder, String operationName) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_NAME.toString(), operationName); } private static void applyHttpClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, Attributes attributes) { String httpUrl = getStableOrOldAttribute(attributes, SemanticAttributes.URL_FULL, SemanticAttributes.HTTP_URL); int defaultPort = getDefaultPortForHttpUrl(httpUrl); String target = getTargetOrDefault(attributes, defaultPort, "Http"); telemetryBuilder.setType("Http"); telemetryBuilder.setTarget(target); Long httpStatusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); if (httpStatusCode != null) { telemetryBuilder.setResultCode(Long.toString(httpStatusCode)); } else { telemetryBuilder.setResultCode("0"); } telemetryBuilder.setData(httpUrl); } private static void applyRpcClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, String rpcSystem, Attributes attributes) { telemetryBuilder.setType(rpcSystem); String target = getTargetOrDefault(attributes, Integer.MAX_VALUE, rpcSystem); telemetryBuilder.setTarget(target); } private static int getDefaultPortForHttpUrl(@Nullable String httpUrl) { if (httpUrl == null) { return Integer.MAX_VALUE; } if (httpUrl.startsWith("https: return 443; } if (httpUrl.startsWith("http: return 80; } return Integer.MAX_VALUE; } public static String getTargetOrDefault( Attributes attributes, int defaultPort, String defaultTarget) { String target = getTargetOrNullStableSemconv(attributes, defaultPort); if (target != null) { return target; } target = getTargetOrNullOldSemconv(attributes, defaultPort); if (target != null) { return target; } return defaultTarget; } @Nullable private static String getTargetOrNullStableSemconv(Attributes attributes, int defaultPort) { String peerService = attributes.get(SemanticAttributes.PEER_SERVICE); if (peerService != null) { return peerService; } String host = attributes.get(SemanticAttributes.SERVER_ADDRESS); if (host != null) { Long port = attributes.get(SemanticAttributes.SERVER_PORT); return getTarget(host, port, defaultPort); } return null; } @Nullable private static String getTargetOrNullOldSemconv(Attributes attributes, int defaultPort) { String peerService = attributes.get(SemanticAttributes.PEER_SERVICE); if (peerService != null) { return peerService; } String host = attributes.get(SemanticAttributes.NET_PEER_NAME); if (host != null) { Long port = attributes.get(SemanticAttributes.NET_PEER_PORT); return getTarget(host, port, defaultPort); } host = attributes.get(SemanticAttributes.NET_SOCK_PEER_NAME); if (host == null) { host = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR); } if (host != null) { Long port = attributes.get(SemanticAttributes.NET_SOCK_PEER_PORT); return getTarget(host, port, defaultPort); } String httpUrl = attributes.get(SemanticAttributes.HTTP_URL); if (httpUrl != null) { return UrlParser.getTarget(httpUrl); } return null; } private static String getTarget(String host, @Nullable Long port, int defaultPort) { if (port != null && port != defaultPort) { return host + ":" + port; } else { return host; } } private static void applyDatabaseClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, String dbSystem, Attributes attributes) { String dbStatement = attributes.get(SemanticAttributes.DB_STATEMENT); if (dbStatement == null) { dbStatement = attributes.get(SemanticAttributes.DB_OPERATION); } String type; if (SQL_DB_SYSTEMS.contains(dbSystem)) { if (dbSystem.equals(SemanticAttributes.DbSystemValues.MYSQL)) { type = "mysql"; } else if (dbSystem.equals(SemanticAttributes.DbSystemValues.POSTGRESQL)) { type = "postgresql"; } else { type = "SQL"; } } else if (dbSystem.equals(COSMOS)) { type = "Microsoft.DocumentDb"; } else { type = dbSystem; } telemetryBuilder.setType(type); telemetryBuilder.setData(dbStatement); String target; String dbName; if (dbSystem.equals(COSMOS)) { String dbUrl = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_URL); if (dbUrl != null) { target = UrlParser.getTarget(dbUrl); } else { target = null; } dbName = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_INSTANCE); } else { target = getTargetOrDefault(attributes, getDefaultPortForDbSystem(dbSystem), dbSystem); dbName = attributes.get(SemanticAttributes.DB_NAME); } target = nullAwareConcat(target, dbName, " | "); if (target == null) { target = dbSystem; } telemetryBuilder.setTarget(target); } private static void applyMessagingClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, SpanKind spanKind, String messagingSystem, Attributes attributes) { if (spanKind == SpanKind.PRODUCER) { telemetryBuilder.setType("Queue Message | " + messagingSystem); } else { telemetryBuilder.setType(messagingSystem); } telemetryBuilder.setTarget(getMessagingTargetSource(attributes)); } private static int getDefaultPortForDbSystem(String dbSystem) { switch (dbSystem) { case SemanticAttributes.DbSystemValues.MONGODB: return 27017; case SemanticAttributes.DbSystemValues.CASSANDRA: return 9042; case SemanticAttributes.DbSystemValues.REDIS: return 6379; case SemanticAttributes.DbSystemValues.MARIADB: case SemanticAttributes.DbSystemValues.MYSQL: return 3306; case SemanticAttributes.DbSystemValues.MSSQL: return 1433; case SemanticAttributes.DbSystemValues.DB2: return 50000; case SemanticAttributes.DbSystemValues.ORACLE: return 1521; case SemanticAttributes.DbSystemValues.H2: return 8082; case SemanticAttributes.DbSystemValues.DERBY: return 1527; case SemanticAttributes.DbSystemValues.POSTGRESQL: return 5432; default: return Integer.MAX_VALUE; } } private TelemetryItem exportRequest(SpanData span, @Nullable Long itemCount) { RequestTelemetryBuilder telemetryBuilder = RequestTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); Attributes attributes = span.getAttributes(); long startEpochNanos = span.getStartEpochNanos(); telemetryBuilder.setId(span.getSpanId()); setTime(telemetryBuilder, startEpochNanos); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(attributes, telemetryBuilder); addLinks(telemetryBuilder, span.getLinks()); String operationName = getOperationName(span); telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_NAME.toString(), operationName); telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId()); String aiLegacyParentId = span.getAttributes().get(AiSemanticAttributes.LEGACY_PARENT_ID); if (aiLegacyParentId != null) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); } else if (span.getParentSpanContext().isValid()) { telemetryBuilder.addTag( ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanContext().getSpanId()); } String aiLegacyRootId = span.getAttributes().get(AiSemanticAttributes.LEGACY_ROOT_ID); if (aiLegacyRootId != null) { telemetryBuilder.addTag("ai_legacyRootID", aiLegacyRootId); } telemetryBuilder.setName(operationName); telemetryBuilder.setDuration( FormattedDuration.fromNanos(span.getEndEpochNanos() - startEpochNanos)); telemetryBuilder.setSuccess(getSuccess(span)); String httpUrl = getHttpUrlFromServerSpan(attributes); if (httpUrl != null) { telemetryBuilder.setUrl(httpUrl); } Long httpStatusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); if (httpStatusCode == null) { httpStatusCode = attributes.get(SemanticAttributes.RPC_GRPC_STATUS_CODE); } if (httpStatusCode != null) { telemetryBuilder.setResponseCode(Long.toString(httpStatusCode)); } else { telemetryBuilder.setResponseCode("0"); } String locationIp = getStableOrOldAttribute(attributes, SemanticAttributes.CLIENT_ADDRESS, SemanticAttributes.HTTP_CLIENT_IP); if (locationIp == null) { locationIp = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR); } if (locationIp != null) { telemetryBuilder.addTag(ContextTagKeys.AI_LOCATION_IP.toString(), locationIp); } telemetryBuilder.setSource(getSource(attributes)); String sessionId = attributes.get(AiSemanticAttributes.SESSION_ID); if (sessionId != null) { telemetryBuilder.addTag(ContextTagKeys.AI_SESSION_ID.toString(), sessionId); } String deviceOs = attributes.get(AiSemanticAttributes.DEVICE_OS); if (deviceOs != null) { telemetryBuilder.addTag(AI_DEVICE_OS.toString(), deviceOs); } String deviceOsVersion = attributes.get(AiSemanticAttributes.DEVICE_OS_VERSION); if (deviceOsVersion != null) { telemetryBuilder.addTag(ContextTagKeys.AI_DEVICE_OS_VERSION.toString(), deviceOsVersion); } if (checkIsPreAggregatedStandardMetric(span)) { telemetryBuilder.addProperty(MS_PROCESSED_BY_METRIC_EXTRACTORS, "True"); } Long enqueuedTime = attributes.get(AiSemanticAttributes.AZURE_SDK_ENQUEUED_TIME); if (enqueuedTime != null) { long timeSinceEnqueuedMillis = Math.max( 0L, NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime)); telemetryBuilder.addMeasurement("timeSinceEnqueued", (double) timeSinceEnqueuedMillis); } Long timeSinceEnqueuedMillis = attributes.get(AiSemanticAttributes.KAFKA_RECORD_QUEUE_TIME_MS); if (timeSinceEnqueuedMillis != null) { telemetryBuilder.addMeasurement("timeSinceEnqueued", (double) timeSinceEnqueuedMillis); } return telemetryBuilder.build(); } private boolean getSuccess(SpanData span) { switch (span.getStatus().getStatusCode()) { case ERROR: return false; case OK: return true; case UNSET: if (captureHttpServer4xxAsError) { Long statusCode = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); return statusCode == null || statusCode < 400; } return true; } return true; } @Nullable public static String getHttpUrlFromServerSpan(Attributes attributes) { String httpUrl = getHttpUrlFromServerSpanStableSemconv(attributes); if (httpUrl != null) { return httpUrl; } return getHttpUrlFromServerSpanOldSemconv(attributes); } @Nullable @Nullable private static String getHttpUrlFromServerSpanOldSemconv(Attributes attributes) { String httpUrl = attributes.get(SemanticAttributes.HTTP_URL); if (httpUrl != null) { return httpUrl; } String scheme = attributes.get(SemanticAttributes.HTTP_SCHEME); if (scheme == null) { return null; } String target = attributes.get(SemanticAttributes.HTTP_TARGET); if (target == null) { return null; } String host = attributes.get(SemanticAttributes.NET_HOST_NAME); Long port = attributes.get(SemanticAttributes.NET_HOST_PORT); if (port != null && port > 0) { return scheme + ": } return scheme + ": } @Nullable private static String getSource(Attributes attributes) { String source = attributes.get(AiSemanticAttributes.SPAN_SOURCE); if (source != null) { return source; } return getMessagingTargetSource(attributes); } @Nullable private static String getMessagingTargetSource(Attributes attributes) { if (isAzureSdkMessaging(attributes.get(AiSemanticAttributes.AZURE_SDK_NAMESPACE))) { String peerAddress = attributes.get(AiSemanticAttributes.AZURE_SDK_PEER_ADDRESS); if (peerAddress != null) { String destination = attributes.get(AiSemanticAttributes.AZURE_SDK_MESSAGE_BUS_DESTINATION); return peerAddress + "/" + destination; } } String messagingSystem = getMessagingSystem(attributes); if (messagingSystem == null) { return null; } String source = nullAwareConcat( getTargetOrNullOldSemconv(attributes, Integer.MAX_VALUE), attributes.get(SemanticAttributes.MESSAGING_DESTINATION_NAME), "/"); if (source != null) { return source; } return messagingSystem; } private static boolean isAzureSdkMessaging(String messagingSystem) { return "Microsoft.EventHub".equals(messagingSystem) || "Microsoft.ServiceBus".equals(messagingSystem); } private static String getOperationName(SpanData span) { String operationName = span.getAttributes().get(AiSemanticAttributes.OPERATION_NAME); if (operationName != null) { return operationName; } return span.getName(); } private static String nullAwareConcat( @Nullable String str1, @Nullable String str2, String separator) { if (str1 == null) { return str2; } if (str2 == null) { return str1; } return str1 + separator + str2; } private void exportEvents( SpanData span, @Nullable String operationName, @Nullable Long itemCount, Consumer<TelemetryItem> consumer) { for (EventData event : span.getEvents()) { String instrumentationScopeName = span.getInstrumentationScopeInfo().getName(); if (eventSuppressor.test(event, instrumentationScopeName)) { continue; } if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE) != null) { SpanContext parentSpanContext = span.getParentSpanContext(); if (!parentSpanContext.isValid() || parentSpanContext.isRemote()) { String stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); if (stacktrace != null && !shouldSuppress.test(span, event)) { String exceptionLogged = span.getAttributes().get(AiSemanticAttributes.LOGGED_EXCEPTION); if (!stacktrace.equals(exceptionLogged)) { consumer.accept(createExceptionTelemetryItem(event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE), span, operationName, itemCount)); } } } return; } MessageTelemetryBuilder telemetryBuilder = MessageTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getSpanId()); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } else { setOperationName(telemetryBuilder, span.getAttributes()); } setTime(telemetryBuilder, event.getEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(event.getAttributes(), telemetryBuilder); telemetryBuilder.setMessage(event.getName()); consumer.accept(telemetryBuilder.build()); } } private TelemetryItem createExceptionTelemetryItem( String errorStack, SpanData span, @Nullable String operationName, @Nullable Long itemCount) { ExceptionTelemetryBuilder telemetryBuilder = ExceptionTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getSpanId()); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } else { setOperationName(telemetryBuilder, span.getAttributes()); } setTime(telemetryBuilder, span.getEndEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(span.getAttributes(), telemetryBuilder); telemetryBuilder.setExceptions(Exceptions.minimalParse(errorStack)); return telemetryBuilder.build(); } public static <T> T getStableOrOldAttribute(Attributes attributes, AttributeKey<T> stable, AttributeKey<T> old) { T value = attributes.get(stable); if (value != null) { return value; } return attributes.get(old); } private static void setTime(AbstractTelemetryBuilder telemetryBuilder, long epochNanos) { telemetryBuilder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(epochNanos)); } private static void setItemCount(AbstractTelemetryBuilder telemetryBuilder, @Nullable Long itemCount) { if (itemCount != null) { telemetryBuilder.setSampleRate(100.0f / itemCount); } } @Nullable private static Long getItemCount(SpanData span) { return span.getAttributes().get(AiSemanticAttributes.ITEM_COUNT); } private static void addLinks(AbstractTelemetryBuilder telemetryBuilder, List<LinkData> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (LinkData link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getSpanContext().getTraceId()); sb.append("\",\"id\":\""); sb.append(link.getSpanContext().getSpanId()); sb.append("\"}"); first = false; } sb.append("]"); telemetryBuilder.addProperty("_MS.links", sb.toString()); } static void applyCommonTags(MappingsBuilder mappingsBuilder) { mappingsBuilder .exact( SemanticAttributes.ENDUSER_ID.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_USER_ID.toString(), (String) value); } }) .exact( AiSemanticAttributes.PREVIEW_APPLICATION_VERSION.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag( ContextTagKeys.AI_APPLICATION_VER.toString(), (String) value); } }); applyConnectionStringAndRoleNameOverrides(mappingsBuilder); } @SuppressWarnings("deprecation") private static final WarningLogger connectionStringAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_CONNECTION_STRING.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"connectionStringOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") private static final WarningLogger roleNameAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_ROLE_NAME.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"roleNameOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") private static final WarningLogger roleInstanceAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_ROLE_INSTANCE.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please reach out to" + " https: + " case for this."); @SuppressWarnings("deprecation") private static final WarningLogger instrumentationKeyAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_INSTRUMENTATION_KEY.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"connectionStringOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") static void applyConnectionStringAndRoleNameOverrides(MappingsBuilder mappingsBuilder) { mappingsBuilder .exact( AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey(), (telemetryBuilder, value) -> { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); }) .exact( AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); } }) .exact( AiSemanticAttributes.DEPRECATED_CONNECTION_STRING.getKey(), (telemetryBuilder, value) -> { connectionStringAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_ROLE_NAME.getKey(), (telemetryBuilder, value) -> { roleNameAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_ROLE_INSTANCE.getKey(), (telemetryBuilder, value) -> { roleInstanceAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_INSTRUMENTATION_KEY.getKey(), (telemetryBuilder, value) -> { instrumentationKeyAttributeNoLongerSupported.recordWarning(); }); } }
class SpanDataMapper { public static final String MS_PROCESSED_BY_METRIC_EXTRACTORS = "_MS.ProcessedByMetricExtractors"; private static final Set<String> SQL_DB_SYSTEMS = new HashSet<>( asList( SemanticAttributes.DbSystemValues.DB2, SemanticAttributes.DbSystemValues.DERBY, SemanticAttributes.DbSystemValues.MARIADB, SemanticAttributes.DbSystemValues.MSSQL, SemanticAttributes.DbSystemValues.MYSQL, SemanticAttributes.DbSystemValues.ORACLE, SemanticAttributes.DbSystemValues.POSTGRESQL, SemanticAttributes.DbSystemValues.SQLITE, SemanticAttributes.DbSystemValues.OTHER_SQL, SemanticAttributes.DbSystemValues.HSQLDB, SemanticAttributes.DbSystemValues.H2)); private static final String COSMOS = "Cosmos"; private static final Mappings MAPPINGS; private static final ContextTagKeys AI_DEVICE_OS = ContextTagKeys.fromString("ai.device.os"); static { MappingsBuilder mappingsBuilder = new MappingsBuilder(SPAN) .ignoreExact(AiSemanticAttributes.AZURE_SDK_NAMESPACE.getKey()) .ignoreExact(AiSemanticAttributes.AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey()) .ignoreExact(AiSemanticAttributes.AZURE_SDK_ENQUEUED_TIME.getKey()) .ignoreExact(AiSemanticAttributes.KAFKA_RECORD_QUEUE_TIME_MS.getKey()) .ignoreExact(AiSemanticAttributes.KAFKA_OFFSET.getKey()) .exact( SemanticAttributes.USER_AGENT_ORIGINAL.getKey(), (builder, value) -> { if (value instanceof String) { builder.addTag("ai.user.userAgent", (String) value); } }) .ignorePrefix("applicationinsights.internal.") .prefix( "http.request.header.", (telemetryBuilder, key, value) -> { if (value instanceof List) { telemetryBuilder.addProperty(key, Mappings.join((List<?>) value)); } }) .prefix( "http.response.header.", (telemetryBuilder, key, value) -> { if (value instanceof List) { telemetryBuilder.addProperty(key, Mappings.join((List<?>) value)); } }); applyCommonTags(mappingsBuilder); MAPPINGS = mappingsBuilder.build(); } private final boolean captureHttpServer4xxAsError; private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final BiPredicate<EventData, String> eventSuppressor; private final BiPredicate<SpanData, EventData> shouldSuppress; public SpanDataMapper( boolean captureHttpServer4xxAsError, BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, BiPredicate<EventData, String> eventSuppressor, BiPredicate<SpanData, EventData> shouldSuppress) { this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; this.telemetryInitializer = telemetryInitializer; this.eventSuppressor = eventSuppressor; this.shouldSuppress = shouldSuppress; } public TelemetryItem map(SpanData span) { Long itemCount = getItemCount(span); return map(span, itemCount); } public void map(SpanData span, Consumer<TelemetryItem> consumer) { Long itemCount = getItemCount(span); TelemetryItem telemetryItem = map(span, itemCount); consumer.accept(telemetryItem); exportEvents( span, telemetryItem.getTags().get(ContextTagKeys.AI_OPERATION_NAME.toString()), itemCount, consumer); } public TelemetryItem map(SpanData span, @Nullable Long itemCount) { if (RequestChecker.isRequest(span)) { return exportRequest(span, itemCount); } else { return exportRemoteDependency(span, span.getKind() == SpanKind.INTERNAL, itemCount); } } private static boolean checkIsPreAggregatedStandardMetric(SpanData span) { Boolean isPreAggregatedStandardMetric = span.getAttributes().get(AiSemanticAttributes.IS_PRE_AGGREGATED); return isPreAggregatedStandardMetric != null && isPreAggregatedStandardMetric; } private TelemetryItem exportRemoteDependency(SpanData span, boolean inProc, @Nullable Long itemCount) { RemoteDependencyTelemetryBuilder telemetryBuilder = RemoteDependencyTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationTags(telemetryBuilder, span); setTime(telemetryBuilder, span.getStartEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(span.getAttributes(), telemetryBuilder); addLinks(telemetryBuilder, span.getLinks()); telemetryBuilder.setId(span.getSpanId()); telemetryBuilder.setName(getDependencyName(span)); telemetryBuilder.setDuration( FormattedDuration.fromNanos(span.getEndEpochNanos() - span.getStartEpochNanos())); telemetryBuilder.setSuccess(getSuccess(span)); if (inProc) { telemetryBuilder.setType("InProc"); } else { applySemanticConventions(telemetryBuilder, span); } if (checkIsPreAggregatedStandardMetric(span)) { telemetryBuilder.addProperty(MS_PROCESSED_BY_METRIC_EXTRACTORS, "True"); } return telemetryBuilder.build(); } private static final Set<String> DEFAULT_HTTP_SPAN_NAMES = new HashSet<>( asList("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "PATCH")); private static String getDependencyName(SpanData span) { String name = span.getName(); String method = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.HTTP_REQUEST_METHOD, SemanticAttributes.HTTP_METHOD); if (method == null) { return name; } if (!DEFAULT_HTTP_SPAN_NAMES.contains(name)) { return name; } String url = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.URL_FULL, SemanticAttributes.HTTP_URL); if (url == null) { return name; } String path = UrlParser.getPath(url); if (path == null) { return name; } return path.isEmpty() ? method + " /" : method + " " + path; } private static void applySemanticConventions( RemoteDependencyTelemetryBuilder telemetryBuilder, SpanData span) { Attributes attributes = span.getAttributes(); String httpMethod = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_REQUEST_METHOD, SemanticAttributes.HTTP_METHOD); if (httpMethod != null) { applyHttpClientSpan(telemetryBuilder, attributes); return; } String rpcSystem = attributes.get(SemanticAttributes.RPC_SYSTEM); if (rpcSystem != null) { applyRpcClientSpan(telemetryBuilder, rpcSystem, attributes); return; } String dbSystem = attributes.get(SemanticAttributes.DB_SYSTEM); if (dbSystem == null) { dbSystem = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_TYPE); } if (dbSystem != null) { applyDatabaseClientSpan(telemetryBuilder, dbSystem, attributes); return; } String messagingSystem = getMessagingSystem(attributes); if (messagingSystem != null) { applyMessagingClientSpan(telemetryBuilder, span.getKind(), messagingSystem, attributes); return; } String target = getTargetOrDefault(attributes, Integer.MAX_VALUE, null); if (target != null) { telemetryBuilder.setTarget(target); return; } telemetryBuilder.setType("InProc"); } @Nullable private static String getMessagingSystem(Attributes attributes) { String azureNamespace = attributes.get(AiSemanticAttributes.AZURE_SDK_NAMESPACE); if (isAzureSdkMessaging(azureNamespace)) { return azureNamespace; } return attributes.get(SemanticAttributes.MESSAGING_SYSTEM); } private static void setOperationTags(AbstractTelemetryBuilder telemetryBuilder, SpanData span) { setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getParentSpanContext().getSpanId()); setOperationName(telemetryBuilder, span.getAttributes()); } private static void setOperationId(AbstractTelemetryBuilder telemetryBuilder, String traceId) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_ID.toString(), traceId); } private static void setOperationParentId( AbstractTelemetryBuilder telemetryBuilder, String parentSpanId) { if (SpanId.isValid(parentSpanId)) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId); } } private static void setOperationName( AbstractTelemetryBuilder telemetryBuilder, Attributes attributes) { String operationName = attributes.get(AiSemanticAttributes.OPERATION_NAME); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } } private static void setOperationName( AbstractTelemetryBuilder telemetryBuilder, String operationName) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_NAME.toString(), operationName); } private static void applyHttpClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, Attributes attributes) { String httpUrl = getStableOrOldAttribute(attributes, SemanticAttributes.URL_FULL, SemanticAttributes.HTTP_URL); int defaultPort = getDefaultPortForHttpUrl(httpUrl); String target = getTargetOrDefault(attributes, defaultPort, "Http"); telemetryBuilder.setType("Http"); telemetryBuilder.setTarget(target); Long httpStatusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); if (httpStatusCode != null) { telemetryBuilder.setResultCode(Long.toString(httpStatusCode)); } else { telemetryBuilder.setResultCode("0"); } telemetryBuilder.setData(httpUrl); } private static void applyRpcClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, String rpcSystem, Attributes attributes) { telemetryBuilder.setType(rpcSystem); String target = getTargetOrDefault(attributes, Integer.MAX_VALUE, rpcSystem); telemetryBuilder.setTarget(target); } private static int getDefaultPortForHttpUrl(@Nullable String httpUrl) { if (httpUrl == null) { return Integer.MAX_VALUE; } if (httpUrl.startsWith("https: return 443; } if (httpUrl.startsWith("http: return 80; } return Integer.MAX_VALUE; } public static String getTargetOrDefault( Attributes attributes, int defaultPort, String defaultTarget) { String target = getTargetOrNullStableSemconv(attributes, defaultPort); if (target != null) { return target; } target = getTargetOrNullOldSemconv(attributes, defaultPort); if (target != null) { return target; } return defaultTarget; } @Nullable private static String getTargetOrNullStableSemconv(Attributes attributes, int defaultPort) { String peerService = attributes.get(SemanticAttributes.PEER_SERVICE); if (peerService != null) { return peerService; } String host = attributes.get(SemanticAttributes.SERVER_ADDRESS); if (host != null) { Long port = attributes.get(SemanticAttributes.SERVER_PORT); return getTarget(host, port, defaultPort); } return null; } @Nullable private static String getTargetOrNullOldSemconv(Attributes attributes, int defaultPort) { String peerService = attributes.get(SemanticAttributes.PEER_SERVICE); if (peerService != null) { return peerService; } String host = attributes.get(SemanticAttributes.NET_PEER_NAME); if (host != null) { Long port = attributes.get(SemanticAttributes.NET_PEER_PORT); return getTarget(host, port, defaultPort); } host = attributes.get(SemanticAttributes.NET_SOCK_PEER_NAME); if (host == null) { host = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR); } if (host != null) { Long port = attributes.get(SemanticAttributes.NET_SOCK_PEER_PORT); return getTarget(host, port, defaultPort); } String httpUrl = attributes.get(SemanticAttributes.HTTP_URL); if (httpUrl != null) { return UrlParser.getTarget(httpUrl); } return null; } private static String getTarget(String host, @Nullable Long port, int defaultPort) { if (port != null && port != defaultPort) { return host + ":" + port; } else { return host; } } private static void applyDatabaseClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, String dbSystem, Attributes attributes) { String dbStatement = attributes.get(SemanticAttributes.DB_STATEMENT); if (dbStatement == null) { dbStatement = attributes.get(SemanticAttributes.DB_OPERATION); } String type; if (SQL_DB_SYSTEMS.contains(dbSystem)) { if (dbSystem.equals(SemanticAttributes.DbSystemValues.MYSQL)) { type = "mysql"; } else if (dbSystem.equals(SemanticAttributes.DbSystemValues.POSTGRESQL)) { type = "postgresql"; } else { type = "SQL"; } } else if (dbSystem.equals(COSMOS)) { type = "Microsoft.DocumentDb"; } else { type = dbSystem; } telemetryBuilder.setType(type); telemetryBuilder.setData(dbStatement); String target; String dbName; if (dbSystem.equals(COSMOS)) { String dbUrl = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_URL); if (dbUrl != null) { target = UrlParser.getTarget(dbUrl); } else { target = null; } dbName = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_INSTANCE); } else { target = getTargetOrDefault(attributes, getDefaultPortForDbSystem(dbSystem), dbSystem); dbName = attributes.get(SemanticAttributes.DB_NAME); } target = nullAwareConcat(target, dbName, " | "); if (target == null) { target = dbSystem; } telemetryBuilder.setTarget(target); } private static void applyMessagingClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, SpanKind spanKind, String messagingSystem, Attributes attributes) { if (spanKind == SpanKind.PRODUCER) { telemetryBuilder.setType("Queue Message | " + messagingSystem); } else { telemetryBuilder.setType(messagingSystem); } telemetryBuilder.setTarget(getMessagingTargetSource(attributes)); } private static int getDefaultPortForDbSystem(String dbSystem) { switch (dbSystem) { case SemanticAttributes.DbSystemValues.MONGODB: return 27017; case SemanticAttributes.DbSystemValues.CASSANDRA: return 9042; case SemanticAttributes.DbSystemValues.REDIS: return 6379; case SemanticAttributes.DbSystemValues.MARIADB: case SemanticAttributes.DbSystemValues.MYSQL: return 3306; case SemanticAttributes.DbSystemValues.MSSQL: return 1433; case SemanticAttributes.DbSystemValues.DB2: return 50000; case SemanticAttributes.DbSystemValues.ORACLE: return 1521; case SemanticAttributes.DbSystemValues.H2: return 8082; case SemanticAttributes.DbSystemValues.DERBY: return 1527; case SemanticAttributes.DbSystemValues.POSTGRESQL: return 5432; default: return Integer.MAX_VALUE; } } private TelemetryItem exportRequest(SpanData span, @Nullable Long itemCount) { RequestTelemetryBuilder telemetryBuilder = RequestTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); Attributes attributes = span.getAttributes(); long startEpochNanos = span.getStartEpochNanos(); telemetryBuilder.setId(span.getSpanId()); setTime(telemetryBuilder, startEpochNanos); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(attributes, telemetryBuilder); addLinks(telemetryBuilder, span.getLinks()); String operationName = getOperationName(span); telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_NAME.toString(), operationName); telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId()); String aiLegacyParentId = span.getAttributes().get(AiSemanticAttributes.LEGACY_PARENT_ID); if (aiLegacyParentId != null) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); } else if (span.getParentSpanContext().isValid()) { telemetryBuilder.addTag( ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanContext().getSpanId()); } String aiLegacyRootId = span.getAttributes().get(AiSemanticAttributes.LEGACY_ROOT_ID); if (aiLegacyRootId != null) { telemetryBuilder.addTag("ai_legacyRootID", aiLegacyRootId); } telemetryBuilder.setName(operationName); telemetryBuilder.setDuration( FormattedDuration.fromNanos(span.getEndEpochNanos() - startEpochNanos)); telemetryBuilder.setSuccess(getSuccess(span)); String httpUrl = getHttpUrlFromServerSpan(attributes); if (httpUrl != null) { telemetryBuilder.setUrl(httpUrl); } Long httpStatusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); if (httpStatusCode == null) { httpStatusCode = attributes.get(SemanticAttributes.RPC_GRPC_STATUS_CODE); } if (httpStatusCode != null) { telemetryBuilder.setResponseCode(Long.toString(httpStatusCode)); } else { telemetryBuilder.setResponseCode("0"); } String locationIp = getStableOrOldAttribute(attributes, SemanticAttributes.CLIENT_ADDRESS, SemanticAttributes.HTTP_CLIENT_IP); if (locationIp == null) { locationIp = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR); } if (locationIp != null) { telemetryBuilder.addTag(ContextTagKeys.AI_LOCATION_IP.toString(), locationIp); } telemetryBuilder.setSource(getSource(attributes)); String sessionId = attributes.get(AiSemanticAttributes.SESSION_ID); if (sessionId != null) { telemetryBuilder.addTag(ContextTagKeys.AI_SESSION_ID.toString(), sessionId); } String deviceOs = attributes.get(AiSemanticAttributes.DEVICE_OS); if (deviceOs != null) { telemetryBuilder.addTag(AI_DEVICE_OS.toString(), deviceOs); } String deviceOsVersion = attributes.get(AiSemanticAttributes.DEVICE_OS_VERSION); if (deviceOsVersion != null) { telemetryBuilder.addTag(ContextTagKeys.AI_DEVICE_OS_VERSION.toString(), deviceOsVersion); } if (checkIsPreAggregatedStandardMetric(span)) { telemetryBuilder.addProperty(MS_PROCESSED_BY_METRIC_EXTRACTORS, "True"); } Long enqueuedTime = attributes.get(AiSemanticAttributes.AZURE_SDK_ENQUEUED_TIME); if (enqueuedTime != null) { long timeSinceEnqueuedMillis = Math.max( 0L, NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime)); telemetryBuilder.addMeasurement("timeSinceEnqueued", (double) timeSinceEnqueuedMillis); } Long timeSinceEnqueuedMillis = attributes.get(AiSemanticAttributes.KAFKA_RECORD_QUEUE_TIME_MS); if (timeSinceEnqueuedMillis != null) { telemetryBuilder.addMeasurement("timeSinceEnqueued", (double) timeSinceEnqueuedMillis); } return telemetryBuilder.build(); } private boolean getSuccess(SpanData span) { switch (span.getStatus().getStatusCode()) { case ERROR: return false; case OK: return true; case UNSET: if (captureHttpServer4xxAsError) { Long statusCode = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); return statusCode == null || statusCode < 400; } return true; } return true; } @Nullable public static String getHttpUrlFromServerSpan(Attributes attributes) { String httpUrl = getHttpUrlFromServerSpanStableSemconv(attributes); if (httpUrl != null) { return httpUrl; } return getHttpUrlFromServerSpanOldSemconv(attributes); } @Nullable private static boolean isDefaultPortForScheme(Long port, String scheme) { return (port == 80 && scheme.equals("http")) || (port == 443 && scheme.equals("https")); } @Nullable private static String getHttpUrlFromServerSpanOldSemconv(Attributes attributes) { String httpUrl = attributes.get(SemanticAttributes.HTTP_URL); if (httpUrl != null) { return httpUrl; } String scheme = attributes.get(SemanticAttributes.HTTP_SCHEME); if (scheme == null) { return null; } String target = attributes.get(SemanticAttributes.HTTP_TARGET); if (target == null) { return null; } String host = attributes.get(SemanticAttributes.NET_HOST_NAME); Long port = attributes.get(SemanticAttributes.NET_HOST_PORT); if (port != null && port > 0) { return scheme + ": } return scheme + ": } @Nullable private static String getSource(Attributes attributes) { String source = attributes.get(AiSemanticAttributes.SPAN_SOURCE); if (source != null) { return source; } return getMessagingTargetSource(attributes); } @Nullable private static String getMessagingTargetSource(Attributes attributes) { if (isAzureSdkMessaging(attributes.get(AiSemanticAttributes.AZURE_SDK_NAMESPACE))) { String peerAddress = attributes.get(AiSemanticAttributes.AZURE_SDK_PEER_ADDRESS); if (peerAddress != null) { String destination = attributes.get(AiSemanticAttributes.AZURE_SDK_MESSAGE_BUS_DESTINATION); return peerAddress + "/" + destination; } } String messagingSystem = getMessagingSystem(attributes); if (messagingSystem == null) { return null; } String source = nullAwareConcat( getTargetOrNullOldSemconv(attributes, Integer.MAX_VALUE), attributes.get(SemanticAttributes.MESSAGING_DESTINATION_NAME), "/"); if (source != null) { return source; } return messagingSystem; } private static boolean isAzureSdkMessaging(String messagingSystem) { return "Microsoft.EventHub".equals(messagingSystem) || "Microsoft.ServiceBus".equals(messagingSystem); } private static String getOperationName(SpanData span) { String operationName = span.getAttributes().get(AiSemanticAttributes.OPERATION_NAME); if (operationName != null) { return operationName; } return span.getName(); } private static String nullAwareConcat( @Nullable String str1, @Nullable String str2, String separator) { if (str1 == null) { return str2; } if (str2 == null) { return str1; } return str1 + separator + str2; } private void exportEvents( SpanData span, @Nullable String operationName, @Nullable Long itemCount, Consumer<TelemetryItem> consumer) { for (EventData event : span.getEvents()) { String instrumentationScopeName = span.getInstrumentationScopeInfo().getName(); if (eventSuppressor.test(event, instrumentationScopeName)) { continue; } if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE) != null) { SpanContext parentSpanContext = span.getParentSpanContext(); if (!parentSpanContext.isValid() || parentSpanContext.isRemote()) { String stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); if (stacktrace != null && !shouldSuppress.test(span, event)) { String exceptionLogged = span.getAttributes().get(AiSemanticAttributes.LOGGED_EXCEPTION); if (!stacktrace.equals(exceptionLogged)) { consumer.accept(createExceptionTelemetryItem(event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE), span, operationName, itemCount)); } } } return; } MessageTelemetryBuilder telemetryBuilder = MessageTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getSpanId()); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } else { setOperationName(telemetryBuilder, span.getAttributes()); } setTime(telemetryBuilder, event.getEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(event.getAttributes(), telemetryBuilder); telemetryBuilder.setMessage(event.getName()); consumer.accept(telemetryBuilder.build()); } } private TelemetryItem createExceptionTelemetryItem( String errorStack, SpanData span, @Nullable String operationName, @Nullable Long itemCount) { ExceptionTelemetryBuilder telemetryBuilder = ExceptionTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getSpanId()); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } else { setOperationName(telemetryBuilder, span.getAttributes()); } setTime(telemetryBuilder, span.getEndEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(span.getAttributes(), telemetryBuilder); telemetryBuilder.setExceptions(Exceptions.minimalParse(errorStack)); return telemetryBuilder.build(); } public static <T> T getStableOrOldAttribute(Attributes attributes, AttributeKey<T> stable, AttributeKey<T> old) { T value = attributes.get(stable); if (value != null) { return value; } return attributes.get(old); } private static void setTime(AbstractTelemetryBuilder telemetryBuilder, long epochNanos) { telemetryBuilder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(epochNanos)); } private static void setItemCount(AbstractTelemetryBuilder telemetryBuilder, @Nullable Long itemCount) { if (itemCount != null) { telemetryBuilder.setSampleRate(100.0f / itemCount); } } @Nullable private static Long getItemCount(SpanData span) { return span.getAttributes().get(AiSemanticAttributes.ITEM_COUNT); } private static void addLinks(AbstractTelemetryBuilder telemetryBuilder, List<LinkData> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (LinkData link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getSpanContext().getTraceId()); sb.append("\",\"id\":\""); sb.append(link.getSpanContext().getSpanId()); sb.append("\"}"); first = false; } sb.append("]"); telemetryBuilder.addProperty("_MS.links", sb.toString()); } static void applyCommonTags(MappingsBuilder mappingsBuilder) { mappingsBuilder .exact( SemanticAttributes.ENDUSER_ID.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_USER_ID.toString(), (String) value); } }) .exact( AiSemanticAttributes.PREVIEW_APPLICATION_VERSION.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag( ContextTagKeys.AI_APPLICATION_VER.toString(), (String) value); } }); applyConnectionStringAndRoleNameOverrides(mappingsBuilder); } @SuppressWarnings("deprecation") private static final WarningLogger connectionStringAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_CONNECTION_STRING.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"connectionStringOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") private static final WarningLogger roleNameAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_ROLE_NAME.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"roleNameOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") private static final WarningLogger roleInstanceAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_ROLE_INSTANCE.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please reach out to" + " https: + " case for this."); @SuppressWarnings("deprecation") private static final WarningLogger instrumentationKeyAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_INSTRUMENTATION_KEY.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"connectionStringOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") static void applyConnectionStringAndRoleNameOverrides(MappingsBuilder mappingsBuilder) { mappingsBuilder .exact( AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey(), (telemetryBuilder, value) -> { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); }) .exact( AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); } }) .exact( AiSemanticAttributes.DEPRECATED_CONNECTION_STRING.getKey(), (telemetryBuilder, value) -> { connectionStringAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_ROLE_NAME.getKey(), (telemetryBuilder, value) -> { roleNameAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_ROLE_INSTANCE.getKey(), (telemetryBuilder, value) -> { roleInstanceAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_INSTRUMENTATION_KEY.getKey(), (telemetryBuilder, value) -> { instrumentationKeyAttributeNoLongerSupported.recordWarning(); }); } }
I sort of like to be able to see the corresponding ifs here and below when appending
private static String getHttpUrlFromServerSpanStableSemconv(Attributes attributes) { String scheme = attributes.get(SemanticAttributes.URL_SCHEME); if (scheme == null) { return null; } String host = attributes.get(SemanticAttributes.SERVER_ADDRESS); if (host == null) { return null; } Long port = attributes.get(SemanticAttributes.SERVER_PORT); String path = attributes.get(SemanticAttributes.URL_PATH); if (path == null) { return null; } String query = attributes.get(SemanticAttributes.URL_QUERY); int len = scheme.length() + host.length() + path.length(); if (port != null) { len += 6; } if (query != null) { len += query.length() + 1; } StringBuilder sb = new StringBuilder(len); sb.append(scheme); sb.append(": sb.append(host); if (port != null && port > 0) { sb.append(':'); sb.append(port); } sb.append(path); if (query != null) { sb.append('?'); sb.append(query); } return sb.toString(); }
}
private static String getHttpUrlFromServerSpanStableSemconv(Attributes attributes) { String scheme = attributes.get(SemanticAttributes.URL_SCHEME); if (scheme == null) { return null; } String host = attributes.get(SemanticAttributes.SERVER_ADDRESS); if (host == null) { return null; } Long port = attributes.get(SemanticAttributes.SERVER_PORT); String path = attributes.get(SemanticAttributes.URL_PATH); if (path == null) { return null; } String query = attributes.get(SemanticAttributes.URL_QUERY); int len = scheme.length() + host.length() + path.length(); if (port != null) { len += 6; } if (query != null) { len += query.length() + 1; } StringBuilder sb = new StringBuilder(len); sb.append(scheme); sb.append(": sb.append(host); if (port != null && port > 0 && !isDefaultPortForScheme(port, scheme)) { sb.append(':'); sb.append(port); } sb.append(path); if (query != null) { sb.append('?'); sb.append(query); } return sb.toString(); }
class SpanDataMapper { public static final String MS_PROCESSED_BY_METRIC_EXTRACTORS = "_MS.ProcessedByMetricExtractors"; private static final Set<String> SQL_DB_SYSTEMS = new HashSet<>( asList( SemanticAttributes.DbSystemValues.DB2, SemanticAttributes.DbSystemValues.DERBY, SemanticAttributes.DbSystemValues.MARIADB, SemanticAttributes.DbSystemValues.MSSQL, SemanticAttributes.DbSystemValues.MYSQL, SemanticAttributes.DbSystemValues.ORACLE, SemanticAttributes.DbSystemValues.POSTGRESQL, SemanticAttributes.DbSystemValues.SQLITE, SemanticAttributes.DbSystemValues.OTHER_SQL, SemanticAttributes.DbSystemValues.HSQLDB, SemanticAttributes.DbSystemValues.H2)); private static final String COSMOS = "Cosmos"; private static final Mappings MAPPINGS; private static final ContextTagKeys AI_DEVICE_OS = ContextTagKeys.fromString("ai.device.os"); static { MappingsBuilder mappingsBuilder = new MappingsBuilder(SPAN) .ignoreExact(AiSemanticAttributes.AZURE_SDK_NAMESPACE.getKey()) .ignoreExact(AiSemanticAttributes.AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey()) .ignoreExact(AiSemanticAttributes.AZURE_SDK_ENQUEUED_TIME.getKey()) .ignoreExact(AiSemanticAttributes.KAFKA_RECORD_QUEUE_TIME_MS.getKey()) .ignoreExact(AiSemanticAttributes.KAFKA_OFFSET.getKey()) .exact( SemanticAttributes.USER_AGENT_ORIGINAL.getKey(), (builder, value) -> { if (value instanceof String) { builder.addTag("ai.user.userAgent", (String) value); } }) .ignorePrefix("applicationinsights.internal.") .prefix( "http.request.header.", (telemetryBuilder, key, value) -> { if (value instanceof List) { telemetryBuilder.addProperty(key, Mappings.join((List<?>) value)); } }) .prefix( "http.response.header.", (telemetryBuilder, key, value) -> { if (value instanceof List) { telemetryBuilder.addProperty(key, Mappings.join((List<?>) value)); } }); applyCommonTags(mappingsBuilder); MAPPINGS = mappingsBuilder.build(); } private final boolean captureHttpServer4xxAsError; private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final BiPredicate<EventData, String> eventSuppressor; private final BiPredicate<SpanData, EventData> shouldSuppress; public SpanDataMapper( boolean captureHttpServer4xxAsError, BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, BiPredicate<EventData, String> eventSuppressor, BiPredicate<SpanData, EventData> shouldSuppress) { this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; this.telemetryInitializer = telemetryInitializer; this.eventSuppressor = eventSuppressor; this.shouldSuppress = shouldSuppress; } public TelemetryItem map(SpanData span) { Long itemCount = getItemCount(span); return map(span, itemCount); } public void map(SpanData span, Consumer<TelemetryItem> consumer) { Long itemCount = getItemCount(span); TelemetryItem telemetryItem = map(span, itemCount); consumer.accept(telemetryItem); exportEvents( span, telemetryItem.getTags().get(ContextTagKeys.AI_OPERATION_NAME.toString()), itemCount, consumer); } public TelemetryItem map(SpanData span, @Nullable Long itemCount) { if (RequestChecker.isRequest(span)) { return exportRequest(span, itemCount); } else { return exportRemoteDependency(span, span.getKind() == SpanKind.INTERNAL, itemCount); } } private static boolean checkIsPreAggregatedStandardMetric(SpanData span) { Boolean isPreAggregatedStandardMetric = span.getAttributes().get(AiSemanticAttributes.IS_PRE_AGGREGATED); return isPreAggregatedStandardMetric != null && isPreAggregatedStandardMetric; } private TelemetryItem exportRemoteDependency(SpanData span, boolean inProc, @Nullable Long itemCount) { RemoteDependencyTelemetryBuilder telemetryBuilder = RemoteDependencyTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationTags(telemetryBuilder, span); setTime(telemetryBuilder, span.getStartEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(span.getAttributes(), telemetryBuilder); addLinks(telemetryBuilder, span.getLinks()); telemetryBuilder.setId(span.getSpanId()); telemetryBuilder.setName(getDependencyName(span)); telemetryBuilder.setDuration( FormattedDuration.fromNanos(span.getEndEpochNanos() - span.getStartEpochNanos())); telemetryBuilder.setSuccess(getSuccess(span)); if (inProc) { telemetryBuilder.setType("InProc"); } else { applySemanticConventions(telemetryBuilder, span); } if (checkIsPreAggregatedStandardMetric(span)) { telemetryBuilder.addProperty(MS_PROCESSED_BY_METRIC_EXTRACTORS, "True"); } return telemetryBuilder.build(); } private static final Set<String> DEFAULT_HTTP_SPAN_NAMES = new HashSet<>( asList("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "PATCH")); private static String getDependencyName(SpanData span) { String name = span.getName(); String method = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.HTTP_REQUEST_METHOD, SemanticAttributes.HTTP_METHOD); if (method == null) { return name; } if (!DEFAULT_HTTP_SPAN_NAMES.contains(name)) { return name; } String url = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.URL_FULL, SemanticAttributes.HTTP_URL); if (url == null) { return name; } String path = UrlParser.getPath(url); if (path == null) { return name; } return path.isEmpty() ? method + " /" : method + " " + path; } private static void applySemanticConventions( RemoteDependencyTelemetryBuilder telemetryBuilder, SpanData span) { Attributes attributes = span.getAttributes(); String httpMethod = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_REQUEST_METHOD, SemanticAttributes.HTTP_METHOD); if (httpMethod != null) { applyHttpClientSpan(telemetryBuilder, attributes); return; } String rpcSystem = attributes.get(SemanticAttributes.RPC_SYSTEM); if (rpcSystem != null) { applyRpcClientSpan(telemetryBuilder, rpcSystem, attributes); return; } String dbSystem = attributes.get(SemanticAttributes.DB_SYSTEM); if (dbSystem == null) { dbSystem = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_TYPE); } if (dbSystem != null) { applyDatabaseClientSpan(telemetryBuilder, dbSystem, attributes); return; } String messagingSystem = getMessagingSystem(attributes); if (messagingSystem != null) { applyMessagingClientSpan(telemetryBuilder, span.getKind(), messagingSystem, attributes); return; } String target = getTargetOrDefault(attributes, Integer.MAX_VALUE, null); if (target != null) { telemetryBuilder.setTarget(target); return; } telemetryBuilder.setType("InProc"); } @Nullable private static String getMessagingSystem(Attributes attributes) { String azureNamespace = attributes.get(AiSemanticAttributes.AZURE_SDK_NAMESPACE); if (isAzureSdkMessaging(azureNamespace)) { return azureNamespace; } return attributes.get(SemanticAttributes.MESSAGING_SYSTEM); } private static void setOperationTags(AbstractTelemetryBuilder telemetryBuilder, SpanData span) { setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getParentSpanContext().getSpanId()); setOperationName(telemetryBuilder, span.getAttributes()); } private static void setOperationId(AbstractTelemetryBuilder telemetryBuilder, String traceId) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_ID.toString(), traceId); } private static void setOperationParentId( AbstractTelemetryBuilder telemetryBuilder, String parentSpanId) { if (SpanId.isValid(parentSpanId)) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId); } } private static void setOperationName( AbstractTelemetryBuilder telemetryBuilder, Attributes attributes) { String operationName = attributes.get(AiSemanticAttributes.OPERATION_NAME); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } } private static void setOperationName( AbstractTelemetryBuilder telemetryBuilder, String operationName) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_NAME.toString(), operationName); } private static void applyHttpClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, Attributes attributes) { String httpUrl = getStableOrOldAttribute(attributes, SemanticAttributes.URL_FULL, SemanticAttributes.HTTP_URL); int defaultPort = getDefaultPortForHttpUrl(httpUrl); String target = getTargetOrDefault(attributes, defaultPort, "Http"); telemetryBuilder.setType("Http"); telemetryBuilder.setTarget(target); Long httpStatusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); if (httpStatusCode != null) { telemetryBuilder.setResultCode(Long.toString(httpStatusCode)); } else { telemetryBuilder.setResultCode("0"); } telemetryBuilder.setData(httpUrl); } private static void applyRpcClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, String rpcSystem, Attributes attributes) { telemetryBuilder.setType(rpcSystem); String target = getTargetOrDefault(attributes, Integer.MAX_VALUE, rpcSystem); telemetryBuilder.setTarget(target); } private static int getDefaultPortForHttpUrl(@Nullable String httpUrl) { if (httpUrl == null) { return Integer.MAX_VALUE; } if (httpUrl.startsWith("https: return 443; } if (httpUrl.startsWith("http: return 80; } return Integer.MAX_VALUE; } public static String getTargetOrDefault( Attributes attributes, int defaultPort, String defaultTarget) { String target = getTargetOrNullStableSemconv(attributes, defaultPort); if (target != null) { return target; } target = getTargetOrNullOldSemconv(attributes, defaultPort); if (target != null) { return target; } return defaultTarget; } @Nullable private static String getTargetOrNullStableSemconv(Attributes attributes, int defaultPort) { String peerService = attributes.get(SemanticAttributes.PEER_SERVICE); if (peerService != null) { return peerService; } String host = attributes.get(SemanticAttributes.SERVER_ADDRESS); if (host != null) { Long port = attributes.get(SemanticAttributes.SERVER_PORT); return getTarget(host, port, defaultPort); } return null; } @Nullable private static String getTargetOrNullOldSemconv(Attributes attributes, int defaultPort) { String peerService = attributes.get(SemanticAttributes.PEER_SERVICE); if (peerService != null) { return peerService; } String host = attributes.get(SemanticAttributes.NET_PEER_NAME); if (host != null) { Long port = attributes.get(SemanticAttributes.NET_PEER_PORT); return getTarget(host, port, defaultPort); } host = attributes.get(SemanticAttributes.NET_SOCK_PEER_NAME); if (host == null) { host = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR); } if (host != null) { Long port = attributes.get(SemanticAttributes.NET_SOCK_PEER_PORT); return getTarget(host, port, defaultPort); } String httpUrl = attributes.get(SemanticAttributes.HTTP_URL); if (httpUrl != null) { return UrlParser.getTarget(httpUrl); } return null; } private static String getTarget(String host, @Nullable Long port, int defaultPort) { if (port != null && port != defaultPort) { return host + ":" + port; } else { return host; } } private static void applyDatabaseClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, String dbSystem, Attributes attributes) { String dbStatement = attributes.get(SemanticAttributes.DB_STATEMENT); if (dbStatement == null) { dbStatement = attributes.get(SemanticAttributes.DB_OPERATION); } String type; if (SQL_DB_SYSTEMS.contains(dbSystem)) { if (dbSystem.equals(SemanticAttributes.DbSystemValues.MYSQL)) { type = "mysql"; } else if (dbSystem.equals(SemanticAttributes.DbSystemValues.POSTGRESQL)) { type = "postgresql"; } else { type = "SQL"; } } else if (dbSystem.equals(COSMOS)) { type = "Microsoft.DocumentDb"; } else { type = dbSystem; } telemetryBuilder.setType(type); telemetryBuilder.setData(dbStatement); String target; String dbName; if (dbSystem.equals(COSMOS)) { String dbUrl = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_URL); if (dbUrl != null) { target = UrlParser.getTarget(dbUrl); } else { target = null; } dbName = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_INSTANCE); } else { target = getTargetOrDefault(attributes, getDefaultPortForDbSystem(dbSystem), dbSystem); dbName = attributes.get(SemanticAttributes.DB_NAME); } target = nullAwareConcat(target, dbName, " | "); if (target == null) { target = dbSystem; } telemetryBuilder.setTarget(target); } private static void applyMessagingClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, SpanKind spanKind, String messagingSystem, Attributes attributes) { if (spanKind == SpanKind.PRODUCER) { telemetryBuilder.setType("Queue Message | " + messagingSystem); } else { telemetryBuilder.setType(messagingSystem); } telemetryBuilder.setTarget(getMessagingTargetSource(attributes)); } private static int getDefaultPortForDbSystem(String dbSystem) { switch (dbSystem) { case SemanticAttributes.DbSystemValues.MONGODB: return 27017; case SemanticAttributes.DbSystemValues.CASSANDRA: return 9042; case SemanticAttributes.DbSystemValues.REDIS: return 6379; case SemanticAttributes.DbSystemValues.MARIADB: case SemanticAttributes.DbSystemValues.MYSQL: return 3306; case SemanticAttributes.DbSystemValues.MSSQL: return 1433; case SemanticAttributes.DbSystemValues.DB2: return 50000; case SemanticAttributes.DbSystemValues.ORACLE: return 1521; case SemanticAttributes.DbSystemValues.H2: return 8082; case SemanticAttributes.DbSystemValues.DERBY: return 1527; case SemanticAttributes.DbSystemValues.POSTGRESQL: return 5432; default: return Integer.MAX_VALUE; } } private TelemetryItem exportRequest(SpanData span, @Nullable Long itemCount) { RequestTelemetryBuilder telemetryBuilder = RequestTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); Attributes attributes = span.getAttributes(); long startEpochNanos = span.getStartEpochNanos(); telemetryBuilder.setId(span.getSpanId()); setTime(telemetryBuilder, startEpochNanos); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(attributes, telemetryBuilder); addLinks(telemetryBuilder, span.getLinks()); String operationName = getOperationName(span); telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_NAME.toString(), operationName); telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId()); String aiLegacyParentId = span.getAttributes().get(AiSemanticAttributes.LEGACY_PARENT_ID); if (aiLegacyParentId != null) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); } else if (span.getParentSpanContext().isValid()) { telemetryBuilder.addTag( ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanContext().getSpanId()); } String aiLegacyRootId = span.getAttributes().get(AiSemanticAttributes.LEGACY_ROOT_ID); if (aiLegacyRootId != null) { telemetryBuilder.addTag("ai_legacyRootID", aiLegacyRootId); } telemetryBuilder.setName(operationName); telemetryBuilder.setDuration( FormattedDuration.fromNanos(span.getEndEpochNanos() - startEpochNanos)); telemetryBuilder.setSuccess(getSuccess(span)); String httpUrl = getHttpUrlFromServerSpan(attributes); if (httpUrl != null) { telemetryBuilder.setUrl(httpUrl); } Long httpStatusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); if (httpStatusCode == null) { httpStatusCode = attributes.get(SemanticAttributes.RPC_GRPC_STATUS_CODE); } if (httpStatusCode != null) { telemetryBuilder.setResponseCode(Long.toString(httpStatusCode)); } else { telemetryBuilder.setResponseCode("0"); } String locationIp = getStableOrOldAttribute(attributes, SemanticAttributes.CLIENT_ADDRESS, SemanticAttributes.HTTP_CLIENT_IP); if (locationIp == null) { locationIp = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR); } if (locationIp != null) { telemetryBuilder.addTag(ContextTagKeys.AI_LOCATION_IP.toString(), locationIp); } telemetryBuilder.setSource(getSource(attributes)); String sessionId = attributes.get(AiSemanticAttributes.SESSION_ID); if (sessionId != null) { telemetryBuilder.addTag(ContextTagKeys.AI_SESSION_ID.toString(), sessionId); } String deviceOs = attributes.get(AiSemanticAttributes.DEVICE_OS); if (deviceOs != null) { telemetryBuilder.addTag(AI_DEVICE_OS.toString(), deviceOs); } String deviceOsVersion = attributes.get(AiSemanticAttributes.DEVICE_OS_VERSION); if (deviceOsVersion != null) { telemetryBuilder.addTag(ContextTagKeys.AI_DEVICE_OS_VERSION.toString(), deviceOsVersion); } if (checkIsPreAggregatedStandardMetric(span)) { telemetryBuilder.addProperty(MS_PROCESSED_BY_METRIC_EXTRACTORS, "True"); } Long enqueuedTime = attributes.get(AiSemanticAttributes.AZURE_SDK_ENQUEUED_TIME); if (enqueuedTime != null) { long timeSinceEnqueuedMillis = Math.max( 0L, NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime)); telemetryBuilder.addMeasurement("timeSinceEnqueued", (double) timeSinceEnqueuedMillis); } Long timeSinceEnqueuedMillis = attributes.get(AiSemanticAttributes.KAFKA_RECORD_QUEUE_TIME_MS); if (timeSinceEnqueuedMillis != null) { telemetryBuilder.addMeasurement("timeSinceEnqueued", (double) timeSinceEnqueuedMillis); } return telemetryBuilder.build(); } private boolean getSuccess(SpanData span) { switch (span.getStatus().getStatusCode()) { case ERROR: return false; case OK: return true; case UNSET: if (captureHttpServer4xxAsError) { Long statusCode = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); return statusCode == null || statusCode < 400; } return true; } return true; } @Nullable public static String getHttpUrlFromServerSpan(Attributes attributes) { String httpUrl = getHttpUrlFromServerSpanStableSemconv(attributes); if (httpUrl != null) { return httpUrl; } return getHttpUrlFromServerSpanOldSemconv(attributes); } @Nullable @Nullable private static String getHttpUrlFromServerSpanOldSemconv(Attributes attributes) { String httpUrl = attributes.get(SemanticAttributes.HTTP_URL); if (httpUrl != null) { return httpUrl; } String scheme = attributes.get(SemanticAttributes.HTTP_SCHEME); if (scheme == null) { return null; } String target = attributes.get(SemanticAttributes.HTTP_TARGET); if (target == null) { return null; } String host = attributes.get(SemanticAttributes.NET_HOST_NAME); Long port = attributes.get(SemanticAttributes.NET_HOST_PORT); if (port != null && port > 0) { return scheme + ": } return scheme + ": } @Nullable private static String getSource(Attributes attributes) { String source = attributes.get(AiSemanticAttributes.SPAN_SOURCE); if (source != null) { return source; } return getMessagingTargetSource(attributes); } @Nullable private static String getMessagingTargetSource(Attributes attributes) { if (isAzureSdkMessaging(attributes.get(AiSemanticAttributes.AZURE_SDK_NAMESPACE))) { String peerAddress = attributes.get(AiSemanticAttributes.AZURE_SDK_PEER_ADDRESS); if (peerAddress != null) { String destination = attributes.get(AiSemanticAttributes.AZURE_SDK_MESSAGE_BUS_DESTINATION); return peerAddress + "/" + destination; } } String messagingSystem = getMessagingSystem(attributes); if (messagingSystem == null) { return null; } String source = nullAwareConcat( getTargetOrNullOldSemconv(attributes, Integer.MAX_VALUE), attributes.get(SemanticAttributes.MESSAGING_DESTINATION_NAME), "/"); if (source != null) { return source; } return messagingSystem; } private static boolean isAzureSdkMessaging(String messagingSystem) { return "Microsoft.EventHub".equals(messagingSystem) || "Microsoft.ServiceBus".equals(messagingSystem); } private static String getOperationName(SpanData span) { String operationName = span.getAttributes().get(AiSemanticAttributes.OPERATION_NAME); if (operationName != null) { return operationName; } return span.getName(); } private static String nullAwareConcat( @Nullable String str1, @Nullable String str2, String separator) { if (str1 == null) { return str2; } if (str2 == null) { return str1; } return str1 + separator + str2; } private void exportEvents( SpanData span, @Nullable String operationName, @Nullable Long itemCount, Consumer<TelemetryItem> consumer) { for (EventData event : span.getEvents()) { String instrumentationScopeName = span.getInstrumentationScopeInfo().getName(); if (eventSuppressor.test(event, instrumentationScopeName)) { continue; } if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE) != null) { SpanContext parentSpanContext = span.getParentSpanContext(); if (!parentSpanContext.isValid() || parentSpanContext.isRemote()) { String stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); if (stacktrace != null && !shouldSuppress.test(span, event)) { String exceptionLogged = span.getAttributes().get(AiSemanticAttributes.LOGGED_EXCEPTION); if (!stacktrace.equals(exceptionLogged)) { consumer.accept(createExceptionTelemetryItem(event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE), span, operationName, itemCount)); } } } return; } MessageTelemetryBuilder telemetryBuilder = MessageTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getSpanId()); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } else { setOperationName(telemetryBuilder, span.getAttributes()); } setTime(telemetryBuilder, event.getEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(event.getAttributes(), telemetryBuilder); telemetryBuilder.setMessage(event.getName()); consumer.accept(telemetryBuilder.build()); } } private TelemetryItem createExceptionTelemetryItem( String errorStack, SpanData span, @Nullable String operationName, @Nullable Long itemCount) { ExceptionTelemetryBuilder telemetryBuilder = ExceptionTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getSpanId()); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } else { setOperationName(telemetryBuilder, span.getAttributes()); } setTime(telemetryBuilder, span.getEndEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(span.getAttributes(), telemetryBuilder); telemetryBuilder.setExceptions(Exceptions.minimalParse(errorStack)); return telemetryBuilder.build(); } public static <T> T getStableOrOldAttribute(Attributes attributes, AttributeKey<T> stable, AttributeKey<T> old) { T value = attributes.get(stable); if (value != null) { return value; } return attributes.get(old); } private static void setTime(AbstractTelemetryBuilder telemetryBuilder, long epochNanos) { telemetryBuilder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(epochNanos)); } private static void setItemCount(AbstractTelemetryBuilder telemetryBuilder, @Nullable Long itemCount) { if (itemCount != null) { telemetryBuilder.setSampleRate(100.0f / itemCount); } } @Nullable private static Long getItemCount(SpanData span) { return span.getAttributes().get(AiSemanticAttributes.ITEM_COUNT); } private static void addLinks(AbstractTelemetryBuilder telemetryBuilder, List<LinkData> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (LinkData link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getSpanContext().getTraceId()); sb.append("\",\"id\":\""); sb.append(link.getSpanContext().getSpanId()); sb.append("\"}"); first = false; } sb.append("]"); telemetryBuilder.addProperty("_MS.links", sb.toString()); } static void applyCommonTags(MappingsBuilder mappingsBuilder) { mappingsBuilder .exact( SemanticAttributes.ENDUSER_ID.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_USER_ID.toString(), (String) value); } }) .exact( AiSemanticAttributes.PREVIEW_APPLICATION_VERSION.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag( ContextTagKeys.AI_APPLICATION_VER.toString(), (String) value); } }); applyConnectionStringAndRoleNameOverrides(mappingsBuilder); } @SuppressWarnings("deprecation") private static final WarningLogger connectionStringAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_CONNECTION_STRING.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"connectionStringOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") private static final WarningLogger roleNameAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_ROLE_NAME.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"roleNameOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") private static final WarningLogger roleInstanceAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_ROLE_INSTANCE.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please reach out to" + " https: + " case for this."); @SuppressWarnings("deprecation") private static final WarningLogger instrumentationKeyAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_INSTRUMENTATION_KEY.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"connectionStringOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") static void applyConnectionStringAndRoleNameOverrides(MappingsBuilder mappingsBuilder) { mappingsBuilder .exact( AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey(), (telemetryBuilder, value) -> { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); }) .exact( AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); } }) .exact( AiSemanticAttributes.DEPRECATED_CONNECTION_STRING.getKey(), (telemetryBuilder, value) -> { connectionStringAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_ROLE_NAME.getKey(), (telemetryBuilder, value) -> { roleNameAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_ROLE_INSTANCE.getKey(), (telemetryBuilder, value) -> { roleInstanceAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_INSTRUMENTATION_KEY.getKey(), (telemetryBuilder, value) -> { instrumentationKeyAttributeNoLongerSupported.recordWarning(); }); } }
class SpanDataMapper { public static final String MS_PROCESSED_BY_METRIC_EXTRACTORS = "_MS.ProcessedByMetricExtractors"; private static final Set<String> SQL_DB_SYSTEMS = new HashSet<>( asList( SemanticAttributes.DbSystemValues.DB2, SemanticAttributes.DbSystemValues.DERBY, SemanticAttributes.DbSystemValues.MARIADB, SemanticAttributes.DbSystemValues.MSSQL, SemanticAttributes.DbSystemValues.MYSQL, SemanticAttributes.DbSystemValues.ORACLE, SemanticAttributes.DbSystemValues.POSTGRESQL, SemanticAttributes.DbSystemValues.SQLITE, SemanticAttributes.DbSystemValues.OTHER_SQL, SemanticAttributes.DbSystemValues.HSQLDB, SemanticAttributes.DbSystemValues.H2)); private static final String COSMOS = "Cosmos"; private static final Mappings MAPPINGS; private static final ContextTagKeys AI_DEVICE_OS = ContextTagKeys.fromString("ai.device.os"); static { MappingsBuilder mappingsBuilder = new MappingsBuilder(SPAN) .ignoreExact(AiSemanticAttributes.AZURE_SDK_NAMESPACE.getKey()) .ignoreExact(AiSemanticAttributes.AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey()) .ignoreExact(AiSemanticAttributes.AZURE_SDK_ENQUEUED_TIME.getKey()) .ignoreExact(AiSemanticAttributes.KAFKA_RECORD_QUEUE_TIME_MS.getKey()) .ignoreExact(AiSemanticAttributes.KAFKA_OFFSET.getKey()) .exact( SemanticAttributes.USER_AGENT_ORIGINAL.getKey(), (builder, value) -> { if (value instanceof String) { builder.addTag("ai.user.userAgent", (String) value); } }) .ignorePrefix("applicationinsights.internal.") .prefix( "http.request.header.", (telemetryBuilder, key, value) -> { if (value instanceof List) { telemetryBuilder.addProperty(key, Mappings.join((List<?>) value)); } }) .prefix( "http.response.header.", (telemetryBuilder, key, value) -> { if (value instanceof List) { telemetryBuilder.addProperty(key, Mappings.join((List<?>) value)); } }); applyCommonTags(mappingsBuilder); MAPPINGS = mappingsBuilder.build(); } private final boolean captureHttpServer4xxAsError; private final BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer; private final BiPredicate<EventData, String> eventSuppressor; private final BiPredicate<SpanData, EventData> shouldSuppress; public SpanDataMapper( boolean captureHttpServer4xxAsError, BiConsumer<AbstractTelemetryBuilder, Resource> telemetryInitializer, BiPredicate<EventData, String> eventSuppressor, BiPredicate<SpanData, EventData> shouldSuppress) { this.captureHttpServer4xxAsError = captureHttpServer4xxAsError; this.telemetryInitializer = telemetryInitializer; this.eventSuppressor = eventSuppressor; this.shouldSuppress = shouldSuppress; } public TelemetryItem map(SpanData span) { Long itemCount = getItemCount(span); return map(span, itemCount); } public void map(SpanData span, Consumer<TelemetryItem> consumer) { Long itemCount = getItemCount(span); TelemetryItem telemetryItem = map(span, itemCount); consumer.accept(telemetryItem); exportEvents( span, telemetryItem.getTags().get(ContextTagKeys.AI_OPERATION_NAME.toString()), itemCount, consumer); } public TelemetryItem map(SpanData span, @Nullable Long itemCount) { if (RequestChecker.isRequest(span)) { return exportRequest(span, itemCount); } else { return exportRemoteDependency(span, span.getKind() == SpanKind.INTERNAL, itemCount); } } private static boolean checkIsPreAggregatedStandardMetric(SpanData span) { Boolean isPreAggregatedStandardMetric = span.getAttributes().get(AiSemanticAttributes.IS_PRE_AGGREGATED); return isPreAggregatedStandardMetric != null && isPreAggregatedStandardMetric; } private TelemetryItem exportRemoteDependency(SpanData span, boolean inProc, @Nullable Long itemCount) { RemoteDependencyTelemetryBuilder telemetryBuilder = RemoteDependencyTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationTags(telemetryBuilder, span); setTime(telemetryBuilder, span.getStartEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(span.getAttributes(), telemetryBuilder); addLinks(telemetryBuilder, span.getLinks()); telemetryBuilder.setId(span.getSpanId()); telemetryBuilder.setName(getDependencyName(span)); telemetryBuilder.setDuration( FormattedDuration.fromNanos(span.getEndEpochNanos() - span.getStartEpochNanos())); telemetryBuilder.setSuccess(getSuccess(span)); if (inProc) { telemetryBuilder.setType("InProc"); } else { applySemanticConventions(telemetryBuilder, span); } if (checkIsPreAggregatedStandardMetric(span)) { telemetryBuilder.addProperty(MS_PROCESSED_BY_METRIC_EXTRACTORS, "True"); } return telemetryBuilder.build(); } private static final Set<String> DEFAULT_HTTP_SPAN_NAMES = new HashSet<>( asList("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "PATCH")); private static String getDependencyName(SpanData span) { String name = span.getName(); String method = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.HTTP_REQUEST_METHOD, SemanticAttributes.HTTP_METHOD); if (method == null) { return name; } if (!DEFAULT_HTTP_SPAN_NAMES.contains(name)) { return name; } String url = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.URL_FULL, SemanticAttributes.HTTP_URL); if (url == null) { return name; } String path = UrlParser.getPath(url); if (path == null) { return name; } return path.isEmpty() ? method + " /" : method + " " + path; } private static void applySemanticConventions( RemoteDependencyTelemetryBuilder telemetryBuilder, SpanData span) { Attributes attributes = span.getAttributes(); String httpMethod = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_REQUEST_METHOD, SemanticAttributes.HTTP_METHOD); if (httpMethod != null) { applyHttpClientSpan(telemetryBuilder, attributes); return; } String rpcSystem = attributes.get(SemanticAttributes.RPC_SYSTEM); if (rpcSystem != null) { applyRpcClientSpan(telemetryBuilder, rpcSystem, attributes); return; } String dbSystem = attributes.get(SemanticAttributes.DB_SYSTEM); if (dbSystem == null) { dbSystem = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_TYPE); } if (dbSystem != null) { applyDatabaseClientSpan(telemetryBuilder, dbSystem, attributes); return; } String messagingSystem = getMessagingSystem(attributes); if (messagingSystem != null) { applyMessagingClientSpan(telemetryBuilder, span.getKind(), messagingSystem, attributes); return; } String target = getTargetOrDefault(attributes, Integer.MAX_VALUE, null); if (target != null) { telemetryBuilder.setTarget(target); return; } telemetryBuilder.setType("InProc"); } @Nullable private static String getMessagingSystem(Attributes attributes) { String azureNamespace = attributes.get(AiSemanticAttributes.AZURE_SDK_NAMESPACE); if (isAzureSdkMessaging(azureNamespace)) { return azureNamespace; } return attributes.get(SemanticAttributes.MESSAGING_SYSTEM); } private static void setOperationTags(AbstractTelemetryBuilder telemetryBuilder, SpanData span) { setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getParentSpanContext().getSpanId()); setOperationName(telemetryBuilder, span.getAttributes()); } private static void setOperationId(AbstractTelemetryBuilder telemetryBuilder, String traceId) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_ID.toString(), traceId); } private static void setOperationParentId( AbstractTelemetryBuilder telemetryBuilder, String parentSpanId) { if (SpanId.isValid(parentSpanId)) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId); } } private static void setOperationName( AbstractTelemetryBuilder telemetryBuilder, Attributes attributes) { String operationName = attributes.get(AiSemanticAttributes.OPERATION_NAME); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } } private static void setOperationName( AbstractTelemetryBuilder telemetryBuilder, String operationName) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_NAME.toString(), operationName); } private static void applyHttpClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, Attributes attributes) { String httpUrl = getStableOrOldAttribute(attributes, SemanticAttributes.URL_FULL, SemanticAttributes.HTTP_URL); int defaultPort = getDefaultPortForHttpUrl(httpUrl); String target = getTargetOrDefault(attributes, defaultPort, "Http"); telemetryBuilder.setType("Http"); telemetryBuilder.setTarget(target); Long httpStatusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); if (httpStatusCode != null) { telemetryBuilder.setResultCode(Long.toString(httpStatusCode)); } else { telemetryBuilder.setResultCode("0"); } telemetryBuilder.setData(httpUrl); } private static void applyRpcClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, String rpcSystem, Attributes attributes) { telemetryBuilder.setType(rpcSystem); String target = getTargetOrDefault(attributes, Integer.MAX_VALUE, rpcSystem); telemetryBuilder.setTarget(target); } private static int getDefaultPortForHttpUrl(@Nullable String httpUrl) { if (httpUrl == null) { return Integer.MAX_VALUE; } if (httpUrl.startsWith("https: return 443; } if (httpUrl.startsWith("http: return 80; } return Integer.MAX_VALUE; } public static String getTargetOrDefault( Attributes attributes, int defaultPort, String defaultTarget) { String target = getTargetOrNullStableSemconv(attributes, defaultPort); if (target != null) { return target; } target = getTargetOrNullOldSemconv(attributes, defaultPort); if (target != null) { return target; } return defaultTarget; } @Nullable private static String getTargetOrNullStableSemconv(Attributes attributes, int defaultPort) { String peerService = attributes.get(SemanticAttributes.PEER_SERVICE); if (peerService != null) { return peerService; } String host = attributes.get(SemanticAttributes.SERVER_ADDRESS); if (host != null) { Long port = attributes.get(SemanticAttributes.SERVER_PORT); return getTarget(host, port, defaultPort); } return null; } @Nullable private static String getTargetOrNullOldSemconv(Attributes attributes, int defaultPort) { String peerService = attributes.get(SemanticAttributes.PEER_SERVICE); if (peerService != null) { return peerService; } String host = attributes.get(SemanticAttributes.NET_PEER_NAME); if (host != null) { Long port = attributes.get(SemanticAttributes.NET_PEER_PORT); return getTarget(host, port, defaultPort); } host = attributes.get(SemanticAttributes.NET_SOCK_PEER_NAME); if (host == null) { host = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR); } if (host != null) { Long port = attributes.get(SemanticAttributes.NET_SOCK_PEER_PORT); return getTarget(host, port, defaultPort); } String httpUrl = attributes.get(SemanticAttributes.HTTP_URL); if (httpUrl != null) { return UrlParser.getTarget(httpUrl); } return null; } private static String getTarget(String host, @Nullable Long port, int defaultPort) { if (port != null && port != defaultPort) { return host + ":" + port; } else { return host; } } private static void applyDatabaseClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, String dbSystem, Attributes attributes) { String dbStatement = attributes.get(SemanticAttributes.DB_STATEMENT); if (dbStatement == null) { dbStatement = attributes.get(SemanticAttributes.DB_OPERATION); } String type; if (SQL_DB_SYSTEMS.contains(dbSystem)) { if (dbSystem.equals(SemanticAttributes.DbSystemValues.MYSQL)) { type = "mysql"; } else if (dbSystem.equals(SemanticAttributes.DbSystemValues.POSTGRESQL)) { type = "postgresql"; } else { type = "SQL"; } } else if (dbSystem.equals(COSMOS)) { type = "Microsoft.DocumentDb"; } else { type = dbSystem; } telemetryBuilder.setType(type); telemetryBuilder.setData(dbStatement); String target; String dbName; if (dbSystem.equals(COSMOS)) { String dbUrl = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_URL); if (dbUrl != null) { target = UrlParser.getTarget(dbUrl); } else { target = null; } dbName = attributes.get(AiSemanticAttributes.AZURE_SDK_DB_INSTANCE); } else { target = getTargetOrDefault(attributes, getDefaultPortForDbSystem(dbSystem), dbSystem); dbName = attributes.get(SemanticAttributes.DB_NAME); } target = nullAwareConcat(target, dbName, " | "); if (target == null) { target = dbSystem; } telemetryBuilder.setTarget(target); } private static void applyMessagingClientSpan( RemoteDependencyTelemetryBuilder telemetryBuilder, SpanKind spanKind, String messagingSystem, Attributes attributes) { if (spanKind == SpanKind.PRODUCER) { telemetryBuilder.setType("Queue Message | " + messagingSystem); } else { telemetryBuilder.setType(messagingSystem); } telemetryBuilder.setTarget(getMessagingTargetSource(attributes)); } private static int getDefaultPortForDbSystem(String dbSystem) { switch (dbSystem) { case SemanticAttributes.DbSystemValues.MONGODB: return 27017; case SemanticAttributes.DbSystemValues.CASSANDRA: return 9042; case SemanticAttributes.DbSystemValues.REDIS: return 6379; case SemanticAttributes.DbSystemValues.MARIADB: case SemanticAttributes.DbSystemValues.MYSQL: return 3306; case SemanticAttributes.DbSystemValues.MSSQL: return 1433; case SemanticAttributes.DbSystemValues.DB2: return 50000; case SemanticAttributes.DbSystemValues.ORACLE: return 1521; case SemanticAttributes.DbSystemValues.H2: return 8082; case SemanticAttributes.DbSystemValues.DERBY: return 1527; case SemanticAttributes.DbSystemValues.POSTGRESQL: return 5432; default: return Integer.MAX_VALUE; } } private TelemetryItem exportRequest(SpanData span, @Nullable Long itemCount) { RequestTelemetryBuilder telemetryBuilder = RequestTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); Attributes attributes = span.getAttributes(); long startEpochNanos = span.getStartEpochNanos(); telemetryBuilder.setId(span.getSpanId()); setTime(telemetryBuilder, startEpochNanos); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(attributes, telemetryBuilder); addLinks(telemetryBuilder, span.getLinks()); String operationName = getOperationName(span); telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_NAME.toString(), operationName); telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId()); String aiLegacyParentId = span.getAttributes().get(AiSemanticAttributes.LEGACY_PARENT_ID); if (aiLegacyParentId != null) { telemetryBuilder.addTag(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); } else if (span.getParentSpanContext().isValid()) { telemetryBuilder.addTag( ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanContext().getSpanId()); } String aiLegacyRootId = span.getAttributes().get(AiSemanticAttributes.LEGACY_ROOT_ID); if (aiLegacyRootId != null) { telemetryBuilder.addTag("ai_legacyRootID", aiLegacyRootId); } telemetryBuilder.setName(operationName); telemetryBuilder.setDuration( FormattedDuration.fromNanos(span.getEndEpochNanos() - startEpochNanos)); telemetryBuilder.setSuccess(getSuccess(span)); String httpUrl = getHttpUrlFromServerSpan(attributes); if (httpUrl != null) { telemetryBuilder.setUrl(httpUrl); } Long httpStatusCode = getStableOrOldAttribute(attributes, SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); if (httpStatusCode == null) { httpStatusCode = attributes.get(SemanticAttributes.RPC_GRPC_STATUS_CODE); } if (httpStatusCode != null) { telemetryBuilder.setResponseCode(Long.toString(httpStatusCode)); } else { telemetryBuilder.setResponseCode("0"); } String locationIp = getStableOrOldAttribute(attributes, SemanticAttributes.CLIENT_ADDRESS, SemanticAttributes.HTTP_CLIENT_IP); if (locationIp == null) { locationIp = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR); } if (locationIp != null) { telemetryBuilder.addTag(ContextTagKeys.AI_LOCATION_IP.toString(), locationIp); } telemetryBuilder.setSource(getSource(attributes)); String sessionId = attributes.get(AiSemanticAttributes.SESSION_ID); if (sessionId != null) { telemetryBuilder.addTag(ContextTagKeys.AI_SESSION_ID.toString(), sessionId); } String deviceOs = attributes.get(AiSemanticAttributes.DEVICE_OS); if (deviceOs != null) { telemetryBuilder.addTag(AI_DEVICE_OS.toString(), deviceOs); } String deviceOsVersion = attributes.get(AiSemanticAttributes.DEVICE_OS_VERSION); if (deviceOsVersion != null) { telemetryBuilder.addTag(ContextTagKeys.AI_DEVICE_OS_VERSION.toString(), deviceOsVersion); } if (checkIsPreAggregatedStandardMetric(span)) { telemetryBuilder.addProperty(MS_PROCESSED_BY_METRIC_EXTRACTORS, "True"); } Long enqueuedTime = attributes.get(AiSemanticAttributes.AZURE_SDK_ENQUEUED_TIME); if (enqueuedTime != null) { long timeSinceEnqueuedMillis = Math.max( 0L, NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime)); telemetryBuilder.addMeasurement("timeSinceEnqueued", (double) timeSinceEnqueuedMillis); } Long timeSinceEnqueuedMillis = attributes.get(AiSemanticAttributes.KAFKA_RECORD_QUEUE_TIME_MS); if (timeSinceEnqueuedMillis != null) { telemetryBuilder.addMeasurement("timeSinceEnqueued", (double) timeSinceEnqueuedMillis); } return telemetryBuilder.build(); } private boolean getSuccess(SpanData span) { switch (span.getStatus().getStatusCode()) { case ERROR: return false; case OK: return true; case UNSET: if (captureHttpServer4xxAsError) { Long statusCode = getStableOrOldAttribute(span.getAttributes(), SemanticAttributes.HTTP_RESPONSE_STATUS_CODE, SemanticAttributes.HTTP_STATUS_CODE); return statusCode == null || statusCode < 400; } return true; } return true; } @Nullable public static String getHttpUrlFromServerSpan(Attributes attributes) { String httpUrl = getHttpUrlFromServerSpanStableSemconv(attributes); if (httpUrl != null) { return httpUrl; } return getHttpUrlFromServerSpanOldSemconv(attributes); } @Nullable private static boolean isDefaultPortForScheme(Long port, String scheme) { return (port == 80 && scheme.equals("http")) || (port == 443 && scheme.equals("https")); } @Nullable private static String getHttpUrlFromServerSpanOldSemconv(Attributes attributes) { String httpUrl = attributes.get(SemanticAttributes.HTTP_URL); if (httpUrl != null) { return httpUrl; } String scheme = attributes.get(SemanticAttributes.HTTP_SCHEME); if (scheme == null) { return null; } String target = attributes.get(SemanticAttributes.HTTP_TARGET); if (target == null) { return null; } String host = attributes.get(SemanticAttributes.NET_HOST_NAME); Long port = attributes.get(SemanticAttributes.NET_HOST_PORT); if (port != null && port > 0) { return scheme + ": } return scheme + ": } @Nullable private static String getSource(Attributes attributes) { String source = attributes.get(AiSemanticAttributes.SPAN_SOURCE); if (source != null) { return source; } return getMessagingTargetSource(attributes); } @Nullable private static String getMessagingTargetSource(Attributes attributes) { if (isAzureSdkMessaging(attributes.get(AiSemanticAttributes.AZURE_SDK_NAMESPACE))) { String peerAddress = attributes.get(AiSemanticAttributes.AZURE_SDK_PEER_ADDRESS); if (peerAddress != null) { String destination = attributes.get(AiSemanticAttributes.AZURE_SDK_MESSAGE_BUS_DESTINATION); return peerAddress + "/" + destination; } } String messagingSystem = getMessagingSystem(attributes); if (messagingSystem == null) { return null; } String source = nullAwareConcat( getTargetOrNullOldSemconv(attributes, Integer.MAX_VALUE), attributes.get(SemanticAttributes.MESSAGING_DESTINATION_NAME), "/"); if (source != null) { return source; } return messagingSystem; } private static boolean isAzureSdkMessaging(String messagingSystem) { return "Microsoft.EventHub".equals(messagingSystem) || "Microsoft.ServiceBus".equals(messagingSystem); } private static String getOperationName(SpanData span) { String operationName = span.getAttributes().get(AiSemanticAttributes.OPERATION_NAME); if (operationName != null) { return operationName; } return span.getName(); } private static String nullAwareConcat( @Nullable String str1, @Nullable String str2, String separator) { if (str1 == null) { return str2; } if (str2 == null) { return str1; } return str1 + separator + str2; } private void exportEvents( SpanData span, @Nullable String operationName, @Nullable Long itemCount, Consumer<TelemetryItem> consumer) { for (EventData event : span.getEvents()) { String instrumentationScopeName = span.getInstrumentationScopeInfo().getName(); if (eventSuppressor.test(event, instrumentationScopeName)) { continue; } if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE) != null) { SpanContext parentSpanContext = span.getParentSpanContext(); if (!parentSpanContext.isValid() || parentSpanContext.isRemote()) { String stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); if (stacktrace != null && !shouldSuppress.test(span, event)) { String exceptionLogged = span.getAttributes().get(AiSemanticAttributes.LOGGED_EXCEPTION); if (!stacktrace.equals(exceptionLogged)) { consumer.accept(createExceptionTelemetryItem(event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE), span, operationName, itemCount)); } } } return; } MessageTelemetryBuilder telemetryBuilder = MessageTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getSpanId()); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } else { setOperationName(telemetryBuilder, span.getAttributes()); } setTime(telemetryBuilder, event.getEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(event.getAttributes(), telemetryBuilder); telemetryBuilder.setMessage(event.getName()); consumer.accept(telemetryBuilder.build()); } } private TelemetryItem createExceptionTelemetryItem( String errorStack, SpanData span, @Nullable String operationName, @Nullable Long itemCount) { ExceptionTelemetryBuilder telemetryBuilder = ExceptionTelemetryBuilder.create(); telemetryInitializer.accept(telemetryBuilder, span.getResource()); setOperationId(telemetryBuilder, span.getTraceId()); setOperationParentId(telemetryBuilder, span.getSpanId()); if (operationName != null) { setOperationName(telemetryBuilder, operationName); } else { setOperationName(telemetryBuilder, span.getAttributes()); } setTime(telemetryBuilder, span.getEndEpochNanos()); setItemCount(telemetryBuilder, itemCount); MAPPINGS.map(span.getAttributes(), telemetryBuilder); telemetryBuilder.setExceptions(Exceptions.minimalParse(errorStack)); return telemetryBuilder.build(); } public static <T> T getStableOrOldAttribute(Attributes attributes, AttributeKey<T> stable, AttributeKey<T> old) { T value = attributes.get(stable); if (value != null) { return value; } return attributes.get(old); } private static void setTime(AbstractTelemetryBuilder telemetryBuilder, long epochNanos) { telemetryBuilder.setTime(FormattedTime.offSetDateTimeFromEpochNanos(epochNanos)); } private static void setItemCount(AbstractTelemetryBuilder telemetryBuilder, @Nullable Long itemCount) { if (itemCount != null) { telemetryBuilder.setSampleRate(100.0f / itemCount); } } @Nullable private static Long getItemCount(SpanData span) { return span.getAttributes().get(AiSemanticAttributes.ITEM_COUNT); } private static void addLinks(AbstractTelemetryBuilder telemetryBuilder, List<LinkData> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (LinkData link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getSpanContext().getTraceId()); sb.append("\",\"id\":\""); sb.append(link.getSpanContext().getSpanId()); sb.append("\"}"); first = false; } sb.append("]"); telemetryBuilder.addProperty("_MS.links", sb.toString()); } static void applyCommonTags(MappingsBuilder mappingsBuilder) { mappingsBuilder .exact( SemanticAttributes.ENDUSER_ID.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_USER_ID.toString(), (String) value); } }) .exact( AiSemanticAttributes.PREVIEW_APPLICATION_VERSION.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag( ContextTagKeys.AI_APPLICATION_VER.toString(), (String) value); } }); applyConnectionStringAndRoleNameOverrides(mappingsBuilder); } @SuppressWarnings("deprecation") private static final WarningLogger connectionStringAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_CONNECTION_STRING.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"connectionStringOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") private static final WarningLogger roleNameAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_ROLE_NAME.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"roleNameOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") private static final WarningLogger roleInstanceAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_ROLE_INSTANCE.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please reach out to" + " https: + " case for this."); @SuppressWarnings("deprecation") private static final WarningLogger instrumentationKeyAttributeNoLongerSupported = new WarningLogger( SpanDataMapper.class, AiSemanticAttributes.DEPRECATED_INSTRUMENTATION_KEY.getKey() + " is no longer supported because it" + " is incompatible with pre-aggregated standard metrics. Please use" + " \"connectionStringOverrides\" configuration, or reach out to" + " https: + " different use case."); @SuppressWarnings("deprecation") static void applyConnectionStringAndRoleNameOverrides(MappingsBuilder mappingsBuilder) { mappingsBuilder .exact( AiSemanticAttributes.INTERNAL_CONNECTION_STRING.getKey(), (telemetryBuilder, value) -> { telemetryBuilder.setConnectionString(ConnectionString.parse((String) value)); }) .exact( AiSemanticAttributes.INTERNAL_ROLE_NAME.getKey(), (telemetryBuilder, value) -> { if (value instanceof String) { telemetryBuilder.addTag(ContextTagKeys.AI_CLOUD_ROLE.toString(), (String) value); } }) .exact( AiSemanticAttributes.DEPRECATED_CONNECTION_STRING.getKey(), (telemetryBuilder, value) -> { connectionStringAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_ROLE_NAME.getKey(), (telemetryBuilder, value) -> { roleNameAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_ROLE_INSTANCE.getKey(), (telemetryBuilder, value) -> { roleInstanceAttributeNoLongerSupported.recordWarning(); }) .exact( AiSemanticAttributes.DEPRECATED_INSTRUMENTATION_KEY.getKey(), (telemetryBuilder, value) -> { instrumentationKeyAttributeNoLongerSupported.recordWarning(); }); } }
Shouldn't 0 be an allowed value? Wouldn't disabling redirects be a valid scenario
public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts() == 0 ? DEFAULT_MAX_REDIRECT_ATTEMPTS : redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); }
this.maxAttempts = redirectOptions.getMaxAttempts() == 0
public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<RequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final Set<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final Set<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new HashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, Set<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); RequestRedirectCondition requestRedirectCondition = new RequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(RequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request was redirected from an invalid redirect allowed method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<HttpRequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final String ORIGINATING_REQUEST_URL_KEY = "orginatingRequestUrl"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); HttpRequestRedirectCondition requestRedirectCondition = new HttpRequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(HttpRequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .addKeyValue(ORIGINATING_REQUEST_URL_KEY, response.getRequest().getUrl()) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request redirection is not enabled for this HTTP method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
Similar comment about log level
private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request was redirected from an invalid redirect allowed method."); return false; } }
.addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod)
private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request redirection is not enabled for this HTTP method."); return false; } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<RequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final Set<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final Set<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts() == 0 ? DEFAULT_MAX_REDIRECT_ATTEMPTS : redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); } @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new HashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, Set<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); RequestRedirectCondition requestRedirectCondition = new RequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(RequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<HttpRequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final String ORIGINATING_REQUEST_URL_KEY = "orginatingRequestUrl"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); } @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); HttpRequestRedirectCondition requestRedirectCondition = new HttpRequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(HttpRequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .addKeyValue(ORIGINATING_REQUEST_URL_KEY, response.getRequest().getUrl()) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
Why do we do a copy of the input EnumSet?
public HttpRedirectOptions(int maxAttempts, HeaderName locationHeader, EnumSet<HttpMethod> allowedRedirectHttpMethods) { if (maxAttempts < 0) { throw LOGGER.atError().log(null, new IllegalArgumentException("Max attempts cannot be less than 0.")); } this.maxAttempts = maxAttempts; this.allowedRedirectHttpMethods = allowedRedirectHttpMethods == null ? EnumSet.noneOf(HttpMethod.class) : EnumSet.copyOf(allowedRedirectHttpMethods); this.locationHeader = locationHeader; }
: EnumSet.copyOf(allowedRedirectHttpMethods);
public HttpRedirectOptions(int maxAttempts, HeaderName locationHeader, EnumSet<HttpMethod> allowedRedirectHttpMethods) { if (maxAttempts < 0) { throw LOGGER.atError().log(null, new IllegalArgumentException("Max attempts cannot be less than 0.")); } this.maxAttempts = maxAttempts; this.allowedRedirectHttpMethods = allowedRedirectHttpMethods == null ? EnumSet.noneOf(HttpMethod.class) : allowedRedirectHttpMethods; this.locationHeader = locationHeader; }
class HttpRedirectOptions { private static final ClientLogger LOGGER = new ClientLogger(HttpRedirectOptions.class); private final int maxAttempts; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; private Predicate<RequestRedirectCondition> shouldRedirectCondition; /** * Creates an instance of {@link HttpRedirectOptions} with values for {@code maxAttempts} * defaulting to 3, if not specified, and the default set of allowed HTTP methods {@link HttpMethod * and {@link HttpMethod * headers. * * @param maxAttempts The maximum number of redirect attempts to be made. * @param allowedRedirectHttpMethods The set of HTTP methods that are allowed to be redirected. * @param locationHeader The header name containing the redirect URL. * @throws IllegalArgumentException if {@code maxAttempts} is less than 0. */ /** * Get the maximum number of redirect attempts to be made. * @return the max redirect attempts. */ public int getMaxAttempts() { return maxAttempts; } /** * Gets the predicate that determines if a redirect should be attempted. * <p> * If null, the default behavior is to redirect HTTP responses with status response code (301, 302, 307, 308). * * @return The predicate that determines if a redirect should be attempted. */ public Predicate<RequestRedirectCondition> getShouldRedirectCondition() { return shouldRedirectCondition; } /** * Sets the predicate that determines if a redirect should be attempted. * <p> * If null, the default behavior is to redirect HTTP responses with status response code (301, 302, 307, 308). * * @param shouldRedirectCondition The predicate that determines if a redirect should be attempted for the given * {@link Response}. * @return The updated {@link HttpRedirectOptions} object. */ public HttpRedirectOptions setShouldRedirectCondition(Predicate<RequestRedirectCondition> shouldRedirectCondition) { this.shouldRedirectCondition = shouldRedirectCondition; return this; } /** * Gets the set of HTTP methods that are allowed to be redirected. * <p> * If null, the default behavior is to allow GET and HEAD HTTP methods to be redirected. * * @return The set of HTTP methods that are allowed to be redirected. */ public EnumSet<HttpMethod> getAllowedRedirectHttpMethods() { return allowedRedirectHttpMethods; } /** * Gets the header name containing the redirect URL. * <p> * If null, the default behavior is to use the "Location" header to locate the redirect URL in the response headers. * * @return The header name containing the redirect URL. */ public HeaderName getLocationHeader() { return locationHeader; } }
class HttpRedirectOptions { private static final ClientLogger LOGGER = new ClientLogger(HttpRedirectOptions.class); private final int maxAttempts; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; private Predicate<HttpRequestRedirectCondition> shouldRedirectCondition; /** * Creates an instance of {@link HttpRedirectOptions}. * * @param maxAttempts The maximum number of redirect attempts to be made. * @param allowedRedirectHttpMethods The set of HTTP methods that are allowed to be redirected. * @param locationHeader The header name containing the redirect URL. * @throws IllegalArgumentException if {@code maxAttempts} is less than 0. */ /** * Get the maximum number of redirect attempts to be made. * @return the max redirect attempts. */ public int getMaxAttempts() { return maxAttempts; } /** * Gets the predicate that determines if a redirect should be attempted. * <p> * If null, the default behavior is to redirect HTTP responses with status response code (301, 302, 307, 308). * * @return The predicate that determines if a redirect should be attempted. */ public Predicate<HttpRequestRedirectCondition> getShouldRedirectCondition() { return shouldRedirectCondition; } /** * Sets the predicate that determines if a redirect should be attempted. * <p> * If null, the default behavior is to redirect HTTP responses with status response code (301, 302, 307, 308). * * @param shouldRedirectCondition The predicate that determines if a redirect should be attempted for the given * {@link Response}. * @return The updated {@link HttpRedirectOptions} object. */ public HttpRedirectOptions setShouldRedirectCondition(Predicate<HttpRequestRedirectCondition> shouldRedirectCondition) { this.shouldRedirectCondition = shouldRedirectCondition; return this; } /** * Gets the set of HTTP methods that are allowed to be redirected. * <p> * If null, the default behavior is to allow GET and HEAD HTTP methods to be redirected. * * @return The set of HTTP methods that are allowed to be redirected. */ public EnumSet<HttpMethod> getAllowedRedirectHttpMethods() { return allowedRedirectHttpMethods; } /** * Gets the header name containing the redirect URL. * <p> * If null, the default behavior is to use the "Location" header to locate the redirect URL in the response headers. * * @return The header name containing the redirect URL. */ public HeaderName getLocationHeader() { return locationHeader; } }
This is related to my comment above. The HttpRedirectOptions type should have a no-args constructor to allow for the default values to be used.
public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); }
}
public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<RequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); } @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); RequestRedirectCondition requestRedirectCondition = new RequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(RequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request was redirected from an invalid redirect allowed method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<HttpRequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final String ORIGINATING_REQUEST_URL_KEY = "orginatingRequestUrl"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); } @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); HttpRequestRedirectCondition requestRedirectCondition = new HttpRequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(HttpRequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .addKeyValue(ORIGINATING_REQUEST_URL_KEY, response.getRequest().getUrl()) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request redirection is not enabled for this HTTP method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
We should allow `null` and use default values.
public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); }
this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition();
public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<RequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); RequestRedirectCondition requestRedirectCondition = new RequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(RequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request was redirected from an invalid redirect allowed method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<HttpRequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final String ORIGINATING_REQUEST_URL_KEY = "orginatingRequestUrl"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); HttpRequestRedirectCondition requestRedirectCondition = new HttpRequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(HttpRequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .addKeyValue(ORIGINATING_REQUEST_URL_KEY, response.getRequest().getUrl()) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request redirection is not enabled for this HTTP method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
```suggestion .log(() -> "Request redirection is not enabled for this HTTP method."); ```
private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request was redirected from an invalid redirect allowed method."); return false; } }
.log(() -> "Request was redirected from an invalid redirect allowed method.");
private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request redirection is not enabled for this HTTP method."); return false; } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<RequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); } @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); RequestRedirectCondition requestRedirectCondition = new RequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(RequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<HttpRequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final String ORIGINATING_REQUEST_URL_KEY = "orginatingRequestUrl"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); } @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); HttpRequestRedirectCondition requestRedirectCondition = new HttpRequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(HttpRequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .addKeyValue(ORIGINATING_REQUEST_URL_KEY, response.getRequest().getUrl()) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
We want to use the options route to modify the existing policy options, how would an empty options help. For default redirect policy, users can directly use the no-args RedirectPolicy ?
public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); }
}
public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<RequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); } @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); RequestRedirectCondition requestRedirectCondition = new RequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(RequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request was redirected from an invalid redirect allowed method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<HttpRequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final String ORIGINATING_REQUEST_URL_KEY = "orginatingRequestUrl"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); } @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); HttpRequestRedirectCondition requestRedirectCondition = new HttpRequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(HttpRequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .addKeyValue(ORIGINATING_REQUEST_URL_KEY, response.getRequest().getUrl()) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request redirection is not enabled for this HTTP method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
Wasn't that added to Azure Core because of Jackson? Is that something we want to do all the time?
private static String serialize(ObjectSerializer serializer, Object value) { if (value == null) { return null; } if (value instanceof String) { return (String) value; } else if (value.getClass().isPrimitive() || value.getClass().isEnum() || value instanceof Number || value instanceof Boolean || value instanceof Character || value instanceof DateTimeRfc1123 || value instanceof ExpandableEnum) { return String.valueOf(value); } else if (value instanceof OffsetDateTime) { return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_INSTANT); } else { try (OutputStream outputStream = new ByteArrayOutputStream()) { serializer.serializeToStream(outputStream, value); return outputStream.toString(); } catch (IOException e) { throw new RuntimeException(e); } } }
|| value.getClass().isEnum()
private static String serialize(ObjectSerializer serializer, Object value) { if (value == null) { return null; } if (value instanceof ExpandableEnum) { value = serialize(serializer, ((ExpandableEnum<?>) value).getValue()); } if (value instanceof String) { return (String) value; } else if (value.getClass().isPrimitive() || value.getClass().isEnum() || value instanceof Number || value instanceof Boolean || value instanceof Character || value instanceof DateTimeRfc1123) { return String.valueOf(value); } else if (value instanceof OffsetDateTime) { return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_INSTANT); } else { try (OutputStream outputStream = new ByteArrayOutputStream()) { serializer.serializeToStream(outputStream, value); return outputStream.toString(); } catch (IOException e) { throw new RuntimeException(e); } } }
class && requestOptionsPosition == -1) { requestOptionsPosition = i; }
class && requestOptionsPosition == -1) { requestOptionsPosition = i; }
Talked offline, this should not be null as the overload is expecting a redirectOptions to be not null and valid to apply the configurations.
public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); }
this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition();
public RedirectPolicy(HttpRedirectOptions redirectOptions) { Objects.requireNonNull(redirectOptions, "'redirectOptions' cannot be null."); this.maxAttempts = redirectOptions.getMaxAttempts(); this.shouldRedirectCondition = redirectOptions.getShouldRedirectCondition(); this.allowedRedirectHttpMethods = redirectOptions.getAllowedRedirectHttpMethods().isEmpty() ? DEFAULT_REDIRECT_ALLOWED_METHODS : redirectOptions.getAllowedRedirectHttpMethods(); this.locationHeader = redirectOptions.getLocationHeader() == null ? HeaderName.LOCATION : redirectOptions.getLocationHeader(); }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<RequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); RequestRedirectCondition requestRedirectCondition = new RequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(RequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request was redirected from an invalid redirect allowed method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
class RedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(RedirectPolicy.class); private final int maxAttempts; private final Predicate<HttpRequestRedirectCondition> shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String REDIRECT_URLS_KEY = "redirectUrls"; private static final String ORIGINATING_REQUEST_URL_KEY = "orginatingRequestUrl"; private static final EnumSet<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; private final EnumSet<HttpMethod> allowedRedirectHttpMethods; private final HeaderName locationHeader; /** * Creates {@link RedirectPolicy} with default with a maximum number of redirect attempts 3, * header name "Location" to locate the redirect url in the response headers and {@link HttpMethod * and {@link HttpMethod * This redirect policy uses the redirect status response code (301, 302, 307, 308) to determine if this request * should be redirected. */ public RedirectPolicy() { this(new HttpRedirectOptions(DEFAULT_MAX_REDIRECT_ATTEMPTS, HeaderName.LOCATION, DEFAULT_REDIRECT_ALLOWED_METHODS)); } /** * Creates {@link RedirectPolicy} with the provided {@code redirectOptions} to * determine if this request should be redirected. * * @param redirectOptions The configured {@link HttpRedirectOptions} to modify redirect policy behavior. * * @throws NullPointerException When {@code redirectOptions} is {@code null}. */ @Override public Response<?> process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attemptRedirect(next, 1, new LinkedHashSet<>()); } /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URL. */ private Response<?> attemptRedirect(final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet<String> attemptedRedirectUrls) { Response<?> response = next.clone().process(); HttpRequestRedirectCondition requestRedirectCondition = new HttpRequestRedirectCondition(response, redirectAttempt, attemptedRedirectUrls); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null && defaultShouldAttemptRedirect(requestRedirectCondition))) { createRedirectRequest(response); return attemptRedirect(next, redirectAttempt + 1, attemptedRedirectUrls); } return response; } public boolean defaultShouldAttemptRedirect(HttpRequestRedirectCondition requestRedirectCondition) { Response<?> response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set<String> attemptedRedirectUrls = requestRedirectCondition.getRedirectedUrls(); String redirectUrl = response.getHeaders().getValue(this.locationHeader); if (isValidRedirectStatusCode(response.getStatusCode()) && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(response.getRequest().getHttpMethod()) && redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { LOGGER.atVerbose() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount) .addKeyValue(REDIRECT_URLS_KEY, attemptedRedirectUrls::toString) .addKeyValue(ORIGINATING_REQUEST_URL_KEY, response.getRequest().getUrl()) .log(() -> "Redirecting."); attemptedRedirectUrls.add(redirectUrl); return true; } return false; } /** * Check if the attempt count of the redirect is less than the {@code maxAttempts} * * @param tryCount the try count for the HTTP request associated to the HTTP response. * * @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= this.maxAttempts) { LOGGER.atError() .addKeyValue("maxAttempts", this.maxAttempts) .log(() -> "Redirect attempts have been exhausted."); return false; } return true; } /** * Check if the redirect url provided in the response headers is already attempted. * * @param redirectUrl the redirect url provided in the response header. * @param attemptedRedirectUrls the set containing a list of attempted redirect locations. * * @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect, * {@code false} otherwise. */ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set<String> attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { LOGGER.atError() .addKeyValue(LoggingKeys.REDIRECT_URL_KEY, redirectUrl) .log(() -> "Request was redirected more than once to the same URL."); return true; } return false; } /** * Check if the request http method is a valid redirect method. * * @param httpMethod the http method of the request. * * @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. */ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (allowedRedirectHttpMethods.contains(httpMethod)) { return true; } else { LOGGER.atError() .addKeyValue(LoggingKeys.HTTP_METHOD_KEY, httpMethod) .log(() -> "Request redirection is not enabled for this HTTP method."); return false; } } /** * Checks if the incoming request status code is a valid redirect status code. * * @param statusCode the status code of the incoming request. * * @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. */ private boolean isValidRedirectStatusCode(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == PERMANENT_REDIRECT_STATUS_CODE || statusCode == TEMPORARY_REDIRECT_STATUS_CODE; } private void createRedirectRequest(Response<?> redirectResponse) { redirectResponse.getRequest().getHeaders().remove(HeaderName.AUTHORIZATION); redirectResponse.getRequest().setUrl(redirectResponse.getHeaders().getValue(this.locationHeader)); try { redirectResponse.close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } }
why change to warn here
public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry( this, null, randomUuid().toString(), ManagementFactory.getRuntimeMXBean().getName(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.configs, this.clientTelemetryConfig, this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init().thenEmpty((publisher) -> { logger.warn( "Initialized DocumentClient [{}] with machineId[{}]" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}]", clientId, ClientTelemetry.getMachineId(diagnosticsClientConfig), serviceEndpoint, connectionPolicy, consistencyLevel); }).subscribe(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); ConsistencyLevel effectiveConsistencyLevel = consistencyLevel != null ? consistencyLevel : this.getDefaultConsistencyLevelOfAccount(); boolean updatedDisableSessionCapturing = (ConsistencyLevel.SESSION != effectiveConsistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer.setDisableSessionCapturing(updatedDisableSessionCapturing); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } }
logger.warn(
public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry( this, null, randomUuid().toString(), ManagementFactory.getRuntimeMXBean().getName(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.configs, this.clientTelemetryConfig, this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init().thenEmpty((publisher) -> { logger.warn( "Initialized DocumentClient [{}] with machineId[{}]" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}]", clientId, ClientTelemetry.getMachineId(diagnosticsClientConfig), serviceEndpoint, connectionPolicy, consistencyLevel); }).subscribe(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); ConsistencyLevel effectiveConsistencyLevel = consistencyLevel != null ? consistencyLevel : this.getDefaultConsistencyLevelOfAccount(); boolean updatedDisableSessionCapturing = (ConsistencyLevel.SESSION != effectiveConsistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer.setDisableSessionCapturing(updatedDisableSessionCapturing); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private final static List<String> EMPTY_REGION_LIST = Collections.emptyList(); private final static List<URI> EMPTY_ENDPOINT_LIST = Collections.emptyList(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); private final static ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.CosmosClientTelemetryConfigAccessor telemetryCfgAccessor = ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.getCosmosClientTelemetryConfigAccessor(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsContextHelper.CosmosDiagnosticsContextAccessor ctxAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsContextHelper.getCosmosDiagnosticsContextAccessor(); private final static ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor qryOptAccessor = ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor(); private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final Map<String, Integer> clientMap = new ConcurrentHashMap<>(); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final static Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxGatewayStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private final Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private final ApiType apiType; private final CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig; private final AtomicReference<CosmosDiagnostics> mostRecentlyCreatedDiagnostics = new AtomicReference<>(null); private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; private final CosmosClientTelemetryConfig clientTelemetryConfig; private final String clientCorrelationId; private final SessionRetryOptions sessionRetryOptions; private final boolean sessionCapturingOverrideEnabled; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length == 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { assert(clientTelemetryConfig != null); Boolean clientTelemetryEnabled = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .isSendClientTelemetryToServiceEnabled(clientTelemetryConfig); assert(clientTelemetryEnabled != null); activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.clientCorrelationId = Strings.isNullOrWhiteSpace(clientCorrelationId) ? String.format("%05d",this.clientId): clientCorrelationId; clientMap.put(serviceEndpoint.toString(), clientMap.getOrDefault(serviceEndpoint.toString(), 0) + 1); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withClientMap(clientMap); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); this.cosmosEndToEndOperationLatencyPolicyConfig = cosmosEndToEndOperationLatencyPolicyConfig; this.diagnosticsClientConfig.withEndToEndOperationLatencyPolicy(cosmosEndToEndOperationLatencyPolicyConfig); this.sessionRetryOptions = sessionRetryOptions; logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withConnectionPolicy(this.connectionPolicy); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); this.diagnosticsClientConfig.withProactiveContainerInitConfig(containerProactiveInitConfig); this.diagnosticsClientConfig.withSessionRetryOptions(sessionRetryOptions); this.sessionCapturingOverrideEnabled = sessionCapturingOverrideEnabled; boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; this.clientTelemetryConfig = clientTelemetryConfig; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { CosmosDiagnostics diagnostics = diagnosticsAccessor.create(this, telemetryCfgAccessor.getSamplingRate(this.clientTelemetryConfig)); this.mostRecentlyCreatedDiagnostics.set(diagnostics); return diagnostics; } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { Throwable databaseRefreshErrorSnapshot = this.globalEndpointManager.getLatestDatabaseRefreshError(); if (databaseRefreshErrorSnapshot != null) { logger.error("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: databaseRefreshErrorSnapshot ); throw new RuntimeException("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: databaseRefreshErrorSnapshot); } else { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: } } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { (this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); (this.gatewayProxy).setCollectionCache(this.collectionCache); (this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); (this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations, this.sessionRetryOptions); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public String getClientCorrelationId() { return this.clientCorrelationId; } @Override public String getMachineId() { if (this.diagnosticsClientConfig == null) { return null; } return ClientTelemetry.getMachineId(diagnosticsClientConfig); } @Override public String getUserAgent() { return this.userAgentContainer.getUserAgent(); } @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return mostRecentlyCreatedDiagnostics.get(); } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(QueryFeedOperationState state) { return nonDocumentReadFeed(state, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return qryOptAccessor.getImpl(options).getOperationContextAndListenerTuple(); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, QueryFeedOperationState state, Class<T> klass, ResourceType resourceTypeEnum) { return createQuery(parentResourceLink, sqlQuery, state, klass, resourceTypeEnum, this); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, QueryFeedOperationState state, Class<T> klass, ResourceType resourceTypeEnum, DiagnosticsClientContext innerDiagnosticsFactory) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); CosmosQueryRequestOptions nonNullQueryOptions = state.getQueryOptions(); UUID correlationActivityIdOfRequestOptions = qryOptAccessor .getImpl(nonNullQueryOptions) .getCorrelationActivityId(); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(nonNullQueryOptions)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(nonNullQueryOptions)); final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(innerDiagnosticsFactory, false); state.registerDiagnosticsFactory( diagnosticsFactory::reset, diagnosticsFactory::merge); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( diagnosticsFactory, resourceLink, sqlQuery, state.getQueryOptions(), klass, resourceTypeEnum, queryClient, correlationActivityId, isQueryCancelledOnTimeout), invalidPartitionExceptionRetryPolicy ).flatMap(result -> { diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot()); return Mono.just(result); }) .onErrorMap(throwable -> { diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot()); return throwable; }) .doOnCancel(() -> diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot())); } private <T> Flux<FeedResponse<T>> createQueryInternal( DiagnosticsClientContext diagnosticsClientContext, String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId, final AtomicBoolean isQueryCancelledOnTimeout) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(diagnosticsClientContext, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache, isQueryCancelledOnTimeout); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; Flux<FeedResponse<T>> feedResponseFlux = iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions, resourceTypeEnum, OperationType.Query); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout( feedResponseFlux, endToEndPolicyConfig, options, isQueryCancelledOnTimeout, diagnosticsClientContext); } return feedResponseFlux; }, Queues.SMALL_BUFFER_SIZE, 1); } private static void applyExceptionToMergedDiagnosticsForQuery( CosmosQueryRequestOptions requestOptions, CosmosException exception, DiagnosticsClientContext diagnosticsClientContext) { CosmosDiagnostics mostRecentlyCreatedDiagnostics = diagnosticsClientContext.getMostRecentlyCreatedDiagnostics(); if (mostRecentlyCreatedDiagnostics != null) { BridgeInternal.setCosmosDiagnostics( exception, mostRecentlyCreatedDiagnostics); } else { List<CosmosDiagnostics> cancelledRequestDiagnostics = qryOptAccessor .getCancelledRequestDiagnosticsTracker(requestOptions); if (cancelledRequestDiagnostics != null && !cancelledRequestDiagnostics.isEmpty()) { CosmosDiagnostics aggregratedCosmosDiagnostics = cancelledRequestDiagnostics .stream() .reduce((first, toBeMerged) -> { ClientSideRequestStatistics clientSideRequestStatistics = ImplementationBridgeHelpers .CosmosDiagnosticsHelper .getCosmosDiagnosticsAccessor() .getClientSideRequestStatisticsRaw(first); ClientSideRequestStatistics toBeMergedClientSideRequestStatistics = ImplementationBridgeHelpers .CosmosDiagnosticsHelper .getCosmosDiagnosticsAccessor() .getClientSideRequestStatisticsRaw(first); if (clientSideRequestStatistics == null) { return toBeMerged; } else { clientSideRequestStatistics.mergeClientSideRequestStatistics(toBeMergedClientSideRequestStatistics); return first; } }) .get(); BridgeInternal.setCosmosDiagnostics(exception, aggregratedCosmosDiagnostics); } } } private static <T> Flux<FeedResponse<T>> getFeedResponseFluxWithTimeout( Flux<FeedResponse<T>> feedResponseFlux, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, CosmosQueryRequestOptions requestOptions, final AtomicBoolean isQueryCancelledOnTimeout, DiagnosticsClientContext diagnosticsClientContext) { Duration endToEndTimeout = endToEndPolicyConfig.getEndToEndOperationTimeout(); if (endToEndTimeout.isNegative()) { return feedResponseFlux .timeout(endToEndTimeout) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException cancellationException = getNegativeTimeoutException(null, endToEndTimeout); cancellationException.setStackTrace(throwable.getStackTrace()); isQueryCancelledOnTimeout.set(true); applyExceptionToMergedDiagnosticsForQuery( requestOptions, cancellationException, diagnosticsClientContext); return cancellationException; } return throwable; }); } return feedResponseFlux .timeout(endToEndTimeout) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); isQueryCancelledOnTimeout.set(true); applyExceptionToMergedDiagnosticsForQuery(requestOptions, exception, diagnosticsClientContext); return exception; } return throwable; }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, QueryFeedOperationState state) { return queryDatabases(new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(Paths.DATABASES_ROOT, querySpec, state, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, QueryFeedOperationState state) { return createQuery(databaseLink, new SqlQuerySpec(query), state, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if (options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null) { if (options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } if (options.getDedicatedGatewayRequestOptions().isIntegratedCacheBypassed()) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_BYPASS_CACHE, String.valueOf(options.getDedicatedGatewayRequestOptions().isIntegratedCacheBypassed())); } } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = PartitionKeyHelper.extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType, DiagnosticsClientContext clientContextOverride) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); String trackingId = null; if (options != null) { trackingId = options.getTrackingId(); } ByteBuffer content = InternalObjectNode.serializeJsonToByteBuffer(document, mapper, trackingId); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), operationType, ResourceType.Document, path, requestHeaders, options, content); if (operationType.isWriteOperation() && options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if( options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } if (options != null) { request.requestContext.setExcludeRegions(options.getExcludeRegions()); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } this.populateCapabilitiesHeader(request); if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private void populateCapabilitiesHeader(RxDocumentServiceRequest request) { if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES)) { request .getHeaders() .put(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); } } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Create, (opt, e2ecfg, clientCtxOverride) -> createDocumentCore( collectionLink, document, opt, disableAutomaticIdGeneration, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> createDocumentCore( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); if (nonNullRequestOptions.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal( collectionLink, document, nonNullRequestOptions, disableAutomaticIdGeneration, finalRetryPolicyInstance, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> createDocumentInternal( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy, DiagnosticsClientContext clientContextOverride) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create, clientContextOverride); return requestObs .flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } private static <T> Mono<T> getPointOperationResponseMonoWithE2ETimeout( RequestOptions requestOptions, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, Mono<T> rxDocumentServiceResponseMono, ScopedDiagnosticsFactory scopedDiagnosticsFactory) { requestOptions.setCosmosEndToEndLatencyPolicyConfig(endToEndPolicyConfig); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { Duration endToEndTimeout = endToEndPolicyConfig.getEndToEndOperationTimeout(); if (endToEndTimeout.isNegative()) { CosmosDiagnostics latestCosmosDiagnosticsSnapshot = scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(); if (latestCosmosDiagnosticsSnapshot == null) { scopedDiagnosticsFactory.createDiagnostics(); } return Mono.error(getNegativeTimeoutException(scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(), endToEndTimeout)); } return rxDocumentServiceResponseMono .timeout(endToEndTimeout) .onErrorMap(throwable -> getCancellationExceptionForPointOperations( scopedDiagnosticsFactory, throwable, requestOptions.getMarkE2ETimeoutInRequestContextCallbackHook())); } return rxDocumentServiceResponseMono; } private static Throwable getCancellationExceptionForPointOperations( ScopedDiagnosticsFactory scopedDiagnosticsFactory, Throwable throwable, AtomicReference<Runnable> markE2ETimeoutInRequestContextCallbackHook) { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); if (unwrappedException instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); Runnable actualCallback = markE2ETimeoutInRequestContextCallbackHook.get(); if (actualCallback != null) { logger.trace("Calling actual Mark E2E timeout callback"); actualCallback.run(); } CosmosDiagnostics lastDiagnosticsSnapshot = scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(); if (lastDiagnosticsSnapshot == null) { scopedDiagnosticsFactory.createDiagnostics(); } BridgeInternal.setCosmosDiagnostics(exception, scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics()); return exception; } return throwable; } private static CosmosException getNegativeTimeoutException(CosmosDiagnostics cosmosDiagnostics, Duration negativeTimeout) { checkNotNull(negativeTimeout, "Argument 'negativeTimeout' must not be null"); checkArgument( negativeTimeout.isNegative(), "This exception should only be used for negative timeouts"); String message = String.format("Negative timeout '%s' provided.", negativeTimeout); CosmosException exception = new OperationCancelledException(message, null); BridgeInternal.setSubStatusCode(exception, HttpConstants.SubStatusCodes.NEGATIVE_TIMEOUT_PROVIDED); if (cosmosDiagnostics != null) { BridgeInternal.setCosmosDiagnostics(exception, cosmosDiagnostics); } return exception; } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Upsert, (opt, e2ecfg, clientCtxOverride) -> upsertDocumentCore( collectionLink, document, opt, disableAutomaticIdGeneration, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> upsertDocumentCore( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); if (nonNullRequestOptions.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> upsertDocumentInternal( collectionLink, document, nonNullRequestOptions, disableAutomaticIdGeneration, finalRetryPolicyInstance, scopedDiagnosticsFactory), finalRetryPolicyInstance), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> upsertDocumentInternal( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest( retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert, clientContextOverride); return reqObs .flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Replace, (opt, e2ecfg, clientCtxOverride) -> replaceDocumentCore( documentLink, document, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> replaceDocumentCore( String documentLink, Object document, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); if (nonNullRequestOptions.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy( collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> replaceDocumentInternal( documentLink, document, nonNullRequestOptions, finalRequestRetryPolicy, endToEndPolicyConfig, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> replaceDocumentInternal( String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal( documentLink, typedDocument, options, retryPolicyInstance, clientContextOverride); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Replace, (opt, e2ecfg, clientCtxOverride) -> replaceDocumentCore( document, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> replaceDocumentCore( Document document, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(clientContextOverride); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy( collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs( () -> replaceDocumentInternal( document, options, finalRequestRetryPolicy, endToEndPolicyConfig, clientContextOverride), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal( Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal( document.getSelfLink(), document, options, retryPolicyInstance, clientContextOverride); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal( String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); if (options != null) { String trackingId = options.getTrackingId(); if (trackingId != null && !trackingId.isEmpty()) { document.set(Constants.Properties.TRACKING_ID, trackingId); } } ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs .flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } private CosmosEndToEndOperationLatencyPolicyConfig getEndToEndOperationLatencyPolicyConfig( RequestOptions options, ResourceType resourceType, OperationType operationType) { return this.getEffectiveEndToEndOperationLatencyPolicyConfig( options != null ? options.getCosmosEndToEndLatencyPolicyConfig() : null, resourceType, operationType); } private CosmosEndToEndOperationLatencyPolicyConfig getEffectiveEndToEndOperationLatencyPolicyConfig( CosmosEndToEndOperationLatencyPolicyConfig policyConfig, ResourceType resourceType, OperationType operationType) { if (policyConfig != null) { return policyConfig; } if (resourceType != ResourceType.Document) { return null; } if (!operationType.isPointOperation() && Configs.isDefaultE2ETimeoutDisabledForNonPointOperations()) { return null; } return this.cosmosEndToEndOperationLatencyPolicyConfig; } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Patch, (opt, e2ecfg, clientCtxOverride) -> patchDocumentCore( documentLink, cosmosPatchOperations, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> patchDocumentCore( String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> patchDocumentInternal( documentLink, cosmosPatchOperations, nonNullRequestOptions, documentClientRetryPolicy, scopedDiagnosticsFactory), documentClientRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> patchDocumentInternal( String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap( PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( clientContextOverride, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs .flatMap(req -> patch(request, retryPolicyInstance)) .map(resp -> toResourceResponse(resp, Document.class)); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Delete, (opt, e2ecfg, clientCtxOverride) -> deleteDocumentCore( documentLink, null, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Delete, (opt, e2ecfg, clientCtxOverride) -> deleteDocumentCore( documentLink, internalObjectNode, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> deleteDocumentCore( String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> deleteDocumentInternal( documentLink, internalObjectNode, nonNullRequestOptions, requestRetryPolicy, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> deleteDocumentInternal( String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, internalObjectNode, options, collectionObs); return requestObs .flatMap(req -> this.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { return readDocument(documentLink, options, this); } private Mono<ResourceResponse<Document>> readDocument( String documentLink, RequestOptions options, DiagnosticsClientContext innerDiagnosticsFactory) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Read, (opt, e2ecfg, clientCtxOverride) -> readDocumentCore(documentLink, opt, e2ecfg, clientCtxOverride), options, false, innerDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> readDocumentCore( String documentLink, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> readDocumentInternal( documentLink, nonNullRequestOptions, retryPolicyInstance, scopedDiagnosticsFactory), retryPolicyInstance), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> readDocumentInternal( String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Read, ResourceType.Document, path, requestHeaders, options); options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this.read(request, retryPolicyInstance) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, QueryFeedOperationState state, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", state, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, QueryFeedOperationState state, Class<T> klass) { final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(this, true); state.registerDiagnosticsFactory( () -> {}, (ctx) -> diagnosticsFactory.merge(ctx) ); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(diagnosticsFactory, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono .flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } itemIdentityList .forEach(itemIdentity -> { if (pkDefinition.getKind().equals(PartitionKind.MULTI_HASH) && ModelBridgeInternal.getPartitionKeyInternal(itemIdentity.getPartitionKey()) .getComponents().size() != pkDefinition.getPaths().size()) { throw new IllegalArgumentException(RMResources.PartitionKeyMismatch); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); Flux<FeedResponse<T>> pointReads = pointReadsForReadMany( diagnosticsFactory, partitionRangeItemKeyMap, resourceLink, state.getQueryOptions(), klass); Flux<FeedResponse<T>> queries = queryForReadMany( diagnosticsFactory, resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), state.getQueryOptions(), klass, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)); return Flux.merge(pointReads, queries) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); Collection<ClientSideRequestStatistics> aggregateRequestStatistics = new DistinctClientSideRequestStatisticsCollection(); double requestCharge = 0; for (FeedResponse<T> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults()); aggregateRequestStatistics.addAll(diagnosticsAccessor.getClientSideRequestStatistics(page.getCosmosDiagnostics())); } CosmosDiagnostics aggregatedDiagnostics = BridgeInternal.createCosmosDiagnostics(aggregatedQueryMetrics); diagnosticsAccessor.addClientSideDiagnosticsToFeed( aggregatedDiagnostics, aggregateRequestStatistics); state.mergeDiagnosticsContext(); CosmosDiagnosticsContext ctx = state.getDiagnosticsContextSnapshot(); if (ctx != null) { ctxAccessor.recordOperation( ctx, 200, 0, finalList.size(), requestCharge, aggregatedDiagnostics, null ); diagnosticsAccessor .setDiagnosticsContext( aggregatedDiagnostics, ctx); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponseWithQueryMetrics( finalList, headers, aggregatedQueryMetrics, null, false, false, aggregatedDiagnostics); return frp; }); }) .onErrorMap(throwable -> { if (throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException)throwable; CosmosDiagnostics diagnostics = cosmosException.getDiagnostics(); if (diagnostics != null) { state.mergeDiagnosticsContext(); CosmosDiagnosticsContext ctx = state.getDiagnosticsContextSnapshot(); if (ctx != null) { ctxAccessor.recordOperation( ctx, cosmosException.getStatusCode(), cosmosException.getSubStatusCode(), 0, cosmosException.getRequestCharge(), diagnostics, throwable ); diagnosticsAccessor .setDiagnosticsContext( diagnostics, state.getDiagnosticsContextSnapshot()); } } return cosmosException; } return throwable; }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); List<String> partitionKeySelectors = createPkSelectors(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; List<CosmosItemIdentity> cosmosItemIdentityList = entry.getValue(); if (cosmosItemIdentityList.size() > 1) { if (partitionKeySelectors.size() == 1 && partitionKeySelectors.get(0).equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(cosmosItemIdentityList); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelectors); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(List<CosmosItemIdentity> idPartitionKeyPairList) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec( List<CosmosItemIdentity> itemIdentities, List<String> partitionKeySelectors) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); int paramCount = 0; for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object[] pkValues = ModelBridgeInternal.getPartitionKeyInternal(pkValueAsPartitionKey).toObjectArray(); List<List<String>> partitionKeyParams = new ArrayList<>(); int pathCount = 0; for (Object pkComponentValue : pkValues) { String pkParamName = "@param" + paramCount; partitionKeyParams.add(Arrays.asList(partitionKeySelectors.get(pathCount), pkParamName)); parameters.add(new SqlParameter(pkParamName, pkComponentValue)); paramCount++; pathCount++; } String idValue = itemIdentity.getId(); String idParamName = "@param" + paramCount; paramCount++; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); for (List<String> pkParam: partitionKeyParams) { queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(pkParam.get(0)); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParam.get(1)); } queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private List<String> createPkSelectors(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.toList()); } private <T> Flux<FeedResponse<T>> queryForReadMany( ScopedDiagnosticsFactory diagnosticsFactory, String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { if (rangeQueryMap.isEmpty()) { return Flux.empty(); } UUID activityId = randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync( diagnosticsFactory, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum, isQueryCancelledOnTimeout); Flux<FeedResponse<T>> feedResponseFlux = executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions, ResourceType.Document, OperationType.Query); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout( feedResponseFlux, endToEndPolicyConfig, options, isQueryCancelledOnTimeout, diagnosticsFactory); } return feedResponseFlux; } private <T> Flux<FeedResponse<T>> pointReadsForReadMany( ScopedDiagnosticsFactory diagnosticsFactory, Map<PartitionKeyRange, List<CosmosItemIdentity>> singleItemPartitionRequestMap, String resourceLink, CosmosQueryRequestOptions queryRequestOptions, Class<T> klass) { ItemDeserializer effectiveItemDeserializer = getEffectiveItemDeserializer(queryRequestOptions, klass); return Flux.fromIterable(singleItemPartitionRequestMap.values()) .flatMap(cosmosItemIdentityList -> { if (cosmosItemIdentityList.size() == 1) { CosmosItemIdentity firstIdentity = cosmosItemIdentityList.get(0); RequestOptions requestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(queryRequestOptions); requestOptions.setPartitionKey(firstIdentity.getPartitionKey()); return this.readDocument((resourceLink + firstIdentity.getId()), requestOptions, diagnosticsFactory) .flatMap(resourceResponse -> Mono.just( new ImmutablePair<ResourceResponse<Document>, CosmosException>(resourceResponse, null) )) .onErrorResume(throwable -> { Throwable unwrappedThrowable = Exceptions.unwrap(throwable); if (unwrappedThrowable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) unwrappedThrowable; int statusCode = cosmosException.getStatusCode(); int subStatusCode = cosmosException.getSubStatusCode(); if (statusCode == HttpConstants.StatusCodes.NOTFOUND && subStatusCode == HttpConstants.SubStatusCodes.UNKNOWN) { return Mono.just(new ImmutablePair<ResourceResponse<Document>, CosmosException>(null, cosmosException)); } } return Mono.error(unwrappedThrowable); }); } return Mono.empty(); }) .flatMap(resourceResponseToExceptionPair -> { ResourceResponse<Document> resourceResponse = resourceResponseToExceptionPair.getLeft(); CosmosException cosmosException = resourceResponseToExceptionPair.getRight(); FeedResponse<T> feedResponse; if (cosmosException != null) { feedResponse = ModelBridgeInternal.createFeedResponse(new ArrayList<>(), cosmosException.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosException.getDiagnostics()))); } else { CosmosItemResponse<T> cosmosItemResponse = ModelBridgeInternal.createCosmosAsyncItemResponse(resourceResponse, klass, effectiveItemDeserializer); feedResponse = ModelBridgeInternal.createFeedResponse( Arrays.asList(cosmosItemResponse.getItem()), cosmosItemResponse.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosItemResponse.getDiagnostics()))); } return Mono.just(feedResponse); }); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, QueryFeedOperationState state, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), state, classOfT); } private <T> ItemDeserializer getEffectiveItemDeserializer( CosmosQueryRequestOptions queryRequestOptions, Class<T> klass) { Function<JsonNode, T> factoryMethod = queryRequestOptions == null ? null : qryOptAccessor.getImpl(queryRequestOptions).getItemFactoryMethod(klass); if (factoryMethod == null) { return this.itemDeserializer; } return new ItemDeserializer.JsonDeserializer(factoryMethod); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public <T> Mono<T> executeFeedOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, Supplier<DocumentClientRetryPolicy> retryPolicyFactory, RxDocumentServiceRequest req, BiFunction<Supplier<DocumentClientRetryPolicy>, RxDocumentServiceRequest, Mono<T>> feedOperation) { return RxDocumentClientImpl.this.executeFeedOperationWithAvailabilityStrategy( resourceType, operationType, retryPolicyFactory, req, feedOperation ); } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, state, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeedFromPagedFlux(DocumentCollection collection, ChangeFeedOperationState state, Class<T> classOfT) { return queryDocumentChangeFeed(collection, state.getChangeFeedOptions(), classOfT); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, QueryFeedOperationState state, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } final CosmosQueryRequestOptions effectiveOptions = qryOptAccessor.clone(state.getQueryOptions()); RequestOptions nonNullRequestOptions = qryOptAccessor.toRequestOptions(effectiveOptions); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = nonNullRequestOptions.getCosmosEndToEndLatencyPolicyConfig(); List<String> orderedApplicableRegionsForSpeculation = getApplicableRegionsForSpeculation( endToEndPolicyConfig, ResourceType.Document, OperationType.Query, false, nonNullRequestOptions); ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(this, false); if (orderedApplicableRegionsForSpeculation.size() < 2) { state.registerDiagnosticsFactory( () -> {}, (ctx) -> diagnosticsFactory.merge(ctx)); } else { state.registerDiagnosticsFactory( () -> diagnosticsFactory.reset(), (ctx) -> diagnosticsFactory.merge(ctx)); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create( diagnosticsFactory, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); List<String> partitionKeySelectors = createPkSelectors(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, partitionKeySelectors); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(state.getQueryOptions())); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); Flux<FeedResponse<T>> innerFlux = ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( diagnosticsFactory, resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId, isQueryCancelledOnTimeout); }); }, invalidPartitionExceptionRetryPolicy); if (orderedApplicableRegionsForSpeculation.size() < 2) { return innerFlux; } return innerFlux .flatMap(result -> { diagnosticsFactory.merge(nonNullRequestOptions); return Mono.just(result); }) .onErrorMap(throwable -> { diagnosticsFactory.merge(nonNullRequestOptions); return throwable; }) .doOnCancel(() -> diagnosticsFactory.merge(nonNullRequestOptions)); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, QueryFeedOperationState state) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (options != null) { request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, QueryFeedOperationState state) { return queryTriggers(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions( String collectionLink, String query, QueryFeedOperationState state) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions( String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, QueryFeedOperationState state) { return queryConflicts(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, QueryFeedOperationState state) { return queryUsers(databaseLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys( String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys( String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy(null)); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return nonDocumentReadFeed(state, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, QueryFeedOperationState state) { return queryPermissions(userLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(userLink, querySpec, state, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(QueryFeedOperationState state) { return nonDocumentReadFeed(state, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeed( QueryFeedOperationState state, ResourceType resourceType, Class<T> klass, String resourceLink) { return nonDocumentReadFeed(state.getQueryOptions(), resourceType, klass, resourceLink); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> nonDocumentReadFeedInternal(options, resourceType, klass, resourceLink, retryPolicy), retryPolicy); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeedInternal( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink, DocumentClientRetryPolicy retryPolicy) { final CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions(); Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(nonNullOptions); int maxPageSize = maxItemCount != null ? maxItemCount : -1; assert(resourceType != ResourceType.Document); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, nonNullOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> readFeed(request) .map(response -> toFeedResponsePage( response, qryOptAccessor.getImpl(nonNullOptions).getItemFactoryMethod(klass), klass)); return Paginator .getPaginatedQueryResultAsObservable( nonNullOptions, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, QueryFeedOperationState state) { return queryOffers(new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(null, querySpec, state, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } @Override public GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } @Override public AddressSelector getAddressSelector() { return new AddressSelector(this.addressResolver, this.configs.getProtocol()); } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.useGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); if (ConnectionMode.DIRECT == this.connectionPolicy.getConnectionMode()) { this.storeModel.enableThroughputControl(throughputControlStore); } else { this.gatewayProxy.enableThroughputControl(throughputControlStore); } } this.throughputControlStore.enableThroughputControlGroup(group, throughputQueryMono); } @Override public Flux<Void> submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig) { return this.storeModel.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig); } @Override public ConsistencyLevel getDefaultConsistencyLevelOfAccount() { return this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } /*** * Configure fault injector provider. * * @param injectorProvider the fault injector provider. */ @Override public void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) { checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null"); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.DIRECT) { this.storeModel.configureFaultInjectorProvider(injectorProvider, this.configs); this.addressResolver.configureFaultInjectorProvider(injectorProvider, this.configs); } this.gatewayProxy.configureFaultInjectorProvider(injectorProvider, this.configs); } @Override public void recordOpenConnectionsAndInitCachesCompleted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesCompleted(cosmosContainerIdentities); } @Override public void recordOpenConnectionsAndInitCachesStarted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesStarted(cosmosContainerIdentities); } @Override public String getMasterKeyOrResourceToken() { return this.masterKeyOrResourceToken; } private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, List<String> partitionKeySelectors) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object[] pkValues = ModelBridgeInternal.getPartitionKeyInternal(partitionKey).toObjectArray(); String pkParamNamePrefix = "@pkValue"; for (int i = 0; i < pkValues.length; i++) { StringBuilder subQueryStringBuilder = new StringBuilder(); String sqlParameterName = pkParamNamePrefix + i; if (i > 0) { subQueryStringBuilder.append(" AND "); } subQueryStringBuilder.append(" c"); subQueryStringBuilder.append(partitionKeySelectors.get(i)); subQueryStringBuilder.append((" = ")); subQueryStringBuilder.append(sqlParameterName); parameters.add(new SqlParameter(sqlParameterName, pkValues[i])); queryStringBuilder.append(subQueryStringBuilder); } return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink, boolean forceRefresh) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink, forceRefresh), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal( RxDocumentServiceRequest request, String collectionLink, boolean forceRefresh) { logger.debug("getFeedRange collectionLink=[{}] - forceRefresh={}", collectionLink, forceRefresh); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, forceRefresh, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } /** * Creates a type 4 (pseudo randomly generated) UUID. * <p> * The {@link UUID} is generated using a non-cryptographically strong pseudo random number generator. * * @return A randomly generated {@link UUID}. */ public static UUID randomUuid() { return randomUuid(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); } static UUID randomUuid(long msb, long lsb) { msb &= 0xffffffffffff0fffL; msb |= 0x0000000000004000L; lsb &= 0x3fffffffffffffffL; lsb |= 0x8000000000000000L; return new UUID(msb, lsb); } private Mono<ResourceResponse<Document>> wrapPointOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, DocumentPointOperation callback, RequestOptions initialRequestOptions, boolean idempotentWriteRetriesEnabled) { return wrapPointOperationWithAvailabilityStrategy( resourceType, operationType, callback, initialRequestOptions, idempotentWriteRetriesEnabled, this ); } private Mono<ResourceResponse<Document>> wrapPointOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, DocumentPointOperation callback, RequestOptions initialRequestOptions, boolean idempotentWriteRetriesEnabled, DiagnosticsClientContext innerDiagnosticsFactory) { checkNotNull(resourceType, "Argument 'resourceType' must not be null."); checkNotNull(operationType, "Argument 'operationType' must not be null."); checkNotNull(callback, "Argument 'callback' must not be null."); final RequestOptions nonNullRequestOptions = initialRequestOptions != null ? initialRequestOptions : new RequestOptions(); checkArgument( resourceType == ResourceType.Document, "This method can only be used for document point operations."); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(nonNullRequestOptions, resourceType, operationType); List<String> orderedApplicableRegionsForSpeculation = getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, idempotentWriteRetriesEnabled, nonNullRequestOptions); if (orderedApplicableRegionsForSpeculation.size() < 2) { return callback.apply(nonNullRequestOptions, endToEndPolicyConfig, innerDiagnosticsFactory); } ThresholdBasedAvailabilityStrategy availabilityStrategy = (ThresholdBasedAvailabilityStrategy)endToEndPolicyConfig.getAvailabilityStrategy(); List<Mono<NonTransientPointOperationResult>> monoList = new ArrayList<>(); final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(innerDiagnosticsFactory, false); orderedApplicableRegionsForSpeculation .forEach(region -> { RequestOptions clonedOptions = new RequestOptions(nonNullRequestOptions); if (monoList.isEmpty()) { Mono<NonTransientPointOperationResult> initialMonoAcrossAllRegions = callback.apply(clonedOptions, endToEndPolicyConfig, diagnosticsFactory) .map(NonTransientPointOperationResult::new) .onErrorResume( RxDocumentClientImpl::isCosmosException, t -> Mono.just( new NonTransientPointOperationResult( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); if (logger.isDebugEnabled()) { monoList.add(initialMonoAcrossAllRegions.doOnSubscribe(c -> logger.debug( "STARTING to process {} operation in region '{}'", operationType, region))); } else { monoList.add(initialMonoAcrossAllRegions); } } else { clonedOptions.setExcludeRegions( getEffectiveExcludedRegionsForHedging( nonNullRequestOptions.getExcludeRegions(), orderedApplicableRegionsForSpeculation, region) ); Mono<NonTransientPointOperationResult> regionalCrossRegionRetryMono = callback.apply(clonedOptions, endToEndPolicyConfig, diagnosticsFactory) .map(NonTransientPointOperationResult::new) .onErrorResume( RxDocumentClientImpl::isNonTransientCosmosException, t -> Mono.just( new NonTransientPointOperationResult( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); Duration delayForCrossRegionalRetry = (availabilityStrategy) .getThreshold() .plus((availabilityStrategy) .getThresholdStep() .multipliedBy(monoList.size() - 1)); if (logger.isDebugEnabled()) { monoList.add( regionalCrossRegionRetryMono .doOnSubscribe(c -> logger.debug("STARTING to process {} operation in region '{}'", operationType, region)) .delaySubscription(delayForCrossRegionalRetry)); } else { monoList.add( regionalCrossRegionRetryMono .delaySubscription(delayForCrossRegionalRetry)); } } }); return Mono .firstWithValue(monoList) .flatMap(nonTransientResult -> { diagnosticsFactory.merge(nonNullRequestOptions); if (nonTransientResult.isError()) { return Mono.error(nonTransientResult.exception); } return Mono.just(nonTransientResult.response); }) .onErrorMap(throwable -> { Throwable exception = Exceptions.unwrap(throwable); if (exception instanceof NoSuchElementException) { List<Throwable> innerThrowables = Exceptions .unwrapMultiple(exception.getCause()); int index = 0; for (Throwable innerThrowable : innerThrowables) { Throwable innerException = Exceptions.unwrap(innerThrowable); if (innerException instanceof CosmosException) { CosmosException cosmosException = Utils.as(innerException, CosmosException.class); diagnosticsFactory.merge(nonNullRequestOptions); return cosmosException; } else if (innerException instanceof NoSuchElementException) { logger.trace( "Operation in {} completed with empty result because it was cancelled.", orderedApplicableRegionsForSpeculation.get(index)); } else if (logger.isWarnEnabled()) { String message = "Unexpected Non-CosmosException when processing operation in '" + orderedApplicableRegionsForSpeculation.get(index) + "'."; logger.warn( message, innerException ); } index++; } } diagnosticsFactory.merge(nonNullRequestOptions); return exception; }) .doOnCancel(() -> diagnosticsFactory.merge(nonNullRequestOptions)); } private static boolean isCosmosException(Throwable t) { final Throwable unwrappedException = Exceptions.unwrap(t); return unwrappedException instanceof CosmosException; } private static boolean isNonTransientCosmosException(Throwable t) { final Throwable unwrappedException = Exceptions.unwrap(t); if (!(unwrappedException instanceof CosmosException)) { return false; } CosmosException cosmosException = Utils.as(unwrappedException, CosmosException.class); return isNonTransientResultForHedging( cosmosException.getStatusCode(), cosmosException.getSubStatusCode()); } private List<String> getEffectiveExcludedRegionsForHedging( List<String> initialExcludedRegions, List<String> applicableRegions, String currentRegion) { List<String> effectiveExcludedRegions = new ArrayList<>(); if (initialExcludedRegions != null) { effectiveExcludedRegions.addAll(initialExcludedRegions); } for (String applicableRegion: applicableRegions) { if (!applicableRegion.equals(currentRegion)) { effectiveExcludedRegions.add(applicableRegion); } } return effectiveExcludedRegions; } private static boolean isNonTransientResultForHedging(int statusCode, int subStatusCode) { if (statusCode < HttpConstants.StatusCodes.BADREQUEST) { return true; } if (statusCode == HttpConstants.StatusCodes.REQUEST_TIMEOUT && subStatusCode == HttpConstants.SubStatusCodes.CLIENT_OPERATION_TIMEOUT) { return true; } if (statusCode == HttpConstants.StatusCodes.BADREQUEST || statusCode == HttpConstants.StatusCodes.CONFLICT || statusCode == HttpConstants.StatusCodes.METHOD_NOT_ALLOWED || statusCode == HttpConstants.StatusCodes.PRECONDITION_FAILED || statusCode == HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE || statusCode == HttpConstants.StatusCodes.UNAUTHORIZED) { return true; } if (statusCode == HttpConstants.StatusCodes.NOTFOUND && subStatusCode == HttpConstants.SubStatusCodes.UNKNOWN) { return true; } return false; } private DiagnosticsClientContext getEffectiveClientContext(DiagnosticsClientContext clientContextOverride) { if (clientContextOverride != null) { return clientContextOverride; } return this; } /** * Returns the applicable endpoints ordered by preference list if any * @param operationType - the operationT * @return the applicable endpoints ordered by preference list if any */ private List<URI> getApplicableEndPoints(OperationType operationType, List<String> excludedRegions) { if (operationType.isReadOnlyOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableReadEndpoints(excludedRegions)); } else if (operationType.isWriteOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableWriteEndpoints(excludedRegions)); } return EMPTY_ENDPOINT_LIST; } private static List<URI> withoutNulls(List<URI> orderedEffectiveEndpointsList) { if (orderedEffectiveEndpointsList == null) { return EMPTY_ENDPOINT_LIST; } int i = 0; while (i < orderedEffectiveEndpointsList.size()) { if (orderedEffectiveEndpointsList.get(i) == null) { orderedEffectiveEndpointsList.remove(i); } else { i++; } } return orderedEffectiveEndpointsList; } private List<String> getApplicableRegionsForSpeculation( CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, ResourceType resourceType, OperationType operationType, boolean isIdempotentWriteRetriesEnabled, RequestOptions options) { return getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, isIdempotentWriteRetriesEnabled, options.getExcludeRegions()); } private List<String> getApplicableRegionsForSpeculation( CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, ResourceType resourceType, OperationType operationType, boolean isIdempotentWriteRetriesEnabled, List<String> excludedRegions) { if (endToEndPolicyConfig == null || !endToEndPolicyConfig.isEnabled()) { return EMPTY_REGION_LIST; } if (resourceType != ResourceType.Document) { return EMPTY_REGION_LIST; } if (operationType.isWriteOperation() && !isIdempotentWriteRetriesEnabled) { return EMPTY_REGION_LIST; } if (operationType.isWriteOperation() && !this.globalEndpointManager.canUseMultipleWriteLocations()) { return EMPTY_REGION_LIST; } if (!(endToEndPolicyConfig.getAvailabilityStrategy() instanceof ThresholdBasedAvailabilityStrategy)) { return EMPTY_REGION_LIST; } List<URI> endpoints = getApplicableEndPoints(operationType, excludedRegions); HashSet<String> normalizedExcludedRegions = new HashSet<>(); if (excludedRegions != null) { excludedRegions.forEach(r -> normalizedExcludedRegions.add(r.toLowerCase(Locale.ROOT))); } List<String> orderedRegionsForSpeculation = new ArrayList<>(); endpoints.forEach(uri -> { String regionName = this.globalEndpointManager.getRegionName(uri, operationType); if (!normalizedExcludedRegions.contains(regionName.toLowerCase(Locale.ROOT))) { orderedRegionsForSpeculation.add(regionName); } }); return orderedRegionsForSpeculation; } private <T> Mono<T> executeFeedOperationWithAvailabilityStrategy( final ResourceType resourceType, final OperationType operationType, final Supplier<DocumentClientRetryPolicy> retryPolicyFactory, final RxDocumentServiceRequest req, final BiFunction<Supplier<DocumentClientRetryPolicy>, RxDocumentServiceRequest, Mono<T>> feedOperation ) { checkNotNull(retryPolicyFactory, "Argument 'retryPolicyFactory' must not be null."); checkNotNull(req, "Argument 'req' must not be null."); assert(resourceType == ResourceType.Document); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = this.getEffectiveEndToEndOperationLatencyPolicyConfig( req.requestContext.getEndToEndOperationLatencyPolicyConfig(), resourceType, operationType); List<String> initialExcludedRegions = req.requestContext.getExcludeRegions(); List<String> orderedApplicableRegionsForSpeculation = this.getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, false, initialExcludedRegions ); if (orderedApplicableRegionsForSpeculation.size() < 2) { return feedOperation.apply(retryPolicyFactory, req); } ThresholdBasedAvailabilityStrategy availabilityStrategy = (ThresholdBasedAvailabilityStrategy)endToEndPolicyConfig.getAvailabilityStrategy(); List<Mono<NonTransientFeedOperationResult<T>>> monoList = new ArrayList<>(); orderedApplicableRegionsForSpeculation .forEach(region -> { RxDocumentServiceRequest clonedRequest = req.clone(); if (monoList.isEmpty()) { Mono<NonTransientFeedOperationResult<T>> initialMonoAcrossAllRegions = feedOperation.apply(retryPolicyFactory, clonedRequest) .map(NonTransientFeedOperationResult::new) .onErrorResume( RxDocumentClientImpl::isCosmosException, t -> Mono.just( new NonTransientFeedOperationResult<>( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); if (logger.isDebugEnabled()) { monoList.add(initialMonoAcrossAllRegions.doOnSubscribe(c -> logger.debug( "STARTING to process {} operation in region '{}'", operationType, region))); } else { monoList.add(initialMonoAcrossAllRegions); } } else { clonedRequest.requestContext.setExcludeRegions( getEffectiveExcludedRegionsForHedging( initialExcludedRegions, orderedApplicableRegionsForSpeculation, region) ); Mono<NonTransientFeedOperationResult<T>> regionalCrossRegionRetryMono = feedOperation.apply(retryPolicyFactory, clonedRequest) .map(NonTransientFeedOperationResult::new) .onErrorResume( RxDocumentClientImpl::isNonTransientCosmosException, t -> Mono.just( new NonTransientFeedOperationResult<>( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); Duration delayForCrossRegionalRetry = (availabilityStrategy) .getThreshold() .plus((availabilityStrategy) .getThresholdStep() .multipliedBy(monoList.size() - 1)); if (logger.isDebugEnabled()) { monoList.add( regionalCrossRegionRetryMono .doOnSubscribe(c -> logger.debug("STARTING to process {} operation in region '{}'", operationType, region)) .delaySubscription(delayForCrossRegionalRetry)); } else { monoList.add( regionalCrossRegionRetryMono .delaySubscription(delayForCrossRegionalRetry)); } } }); return Mono .firstWithValue(monoList) .flatMap(nonTransientResult -> { if (nonTransientResult.isError()) { return Mono.error(nonTransientResult.exception); } return Mono.just(nonTransientResult.response); }) .onErrorMap(throwable -> { Throwable exception = Exceptions.unwrap(throwable); if (exception instanceof NoSuchElementException) { List<Throwable> innerThrowables = Exceptions .unwrapMultiple(exception.getCause()); int index = 0; for (Throwable innerThrowable : innerThrowables) { Throwable innerException = Exceptions.unwrap(innerThrowable); if (innerException instanceof CosmosException) { return Utils.as(innerException, CosmosException.class); } else if (innerException instanceof NoSuchElementException) { logger.trace( "Operation in {} completed with empty result because it was cancelled.", orderedApplicableRegionsForSpeculation.get(index)); } else if (logger.isWarnEnabled()) { String message = "Unexpected Non-CosmosException when processing operation in '" + orderedApplicableRegionsForSpeculation.get(index) + "'."; logger.warn( message, innerException ); } index++; } } return exception; }); } @FunctionalInterface private interface DocumentPointOperation { Mono<ResourceResponse<Document>> apply(RequestOptions requestOptions, CosmosEndToEndOperationLatencyPolicyConfig endToEndOperationLatencyPolicyConfig, DiagnosticsClientContext clientContextOverride); } private static class NonTransientPointOperationResult { private final ResourceResponse<Document> response; private final CosmosException exception; public NonTransientPointOperationResult(CosmosException exception) { checkNotNull(exception, "Argument 'exception' must not be null."); this.exception = exception; this.response = null; } public NonTransientPointOperationResult(ResourceResponse<Document> response) { checkNotNull(response, "Argument 'response' must not be null."); this.exception = null; this.response = response; } public boolean isError() { return this.exception != null; } public CosmosException getException() { return this.exception; } public ResourceResponse<Document> getResponse() { return this.response; } } private static class NonTransientFeedOperationResult<T> { private final T response; private final CosmosException exception; public NonTransientFeedOperationResult(CosmosException exception) { checkNotNull(exception, "Argument 'exception' must not be null."); this.exception = exception; this.response = null; } public NonTransientFeedOperationResult(T response) { checkNotNull(response, "Argument 'response' must not be null."); this.exception = null; this.response = response; } public boolean isError() { return this.exception != null; } public CosmosException getException() { return this.exception; } public T getResponse() { return this.response; } } private static class ScopedDiagnosticsFactory implements DiagnosticsClientContext { private final AtomicBoolean isMerged = new AtomicBoolean(false); private final DiagnosticsClientContext inner; private final ConcurrentLinkedQueue<CosmosDiagnostics> createdDiagnostics; private final boolean shouldCaptureAllFeedDiagnostics; private final AtomicReference<CosmosDiagnostics> mostRecentlyCreatedDiagnostics = new AtomicReference<>(null); public ScopedDiagnosticsFactory(DiagnosticsClientContext inner, boolean shouldCaptureAllFeedDiagnostics) { checkNotNull(inner, "Argument 'inner' must not be null."); this.inner = inner; this.createdDiagnostics = new ConcurrentLinkedQueue<>(); this.shouldCaptureAllFeedDiagnostics = shouldCaptureAllFeedDiagnostics; } @Override public DiagnosticsClientConfig getConfig() { return inner.getConfig(); } @Override public CosmosDiagnostics createDiagnostics() { CosmosDiagnostics diagnostics = inner.createDiagnostics(); createdDiagnostics.add(diagnostics); mostRecentlyCreatedDiagnostics.set(diagnostics); return diagnostics; } @Override public String getUserAgent() { return inner.getUserAgent(); } @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return this.mostRecentlyCreatedDiagnostics.get(); } public void merge(RequestOptions requestOptions) { CosmosDiagnosticsContext knownCtx = null; if (requestOptions != null) { CosmosDiagnosticsContext ctxSnapshot = requestOptions.getDiagnosticsContextSnapshot(); if (ctxSnapshot != null) { knownCtx = requestOptions.getDiagnosticsContextSnapshot(); } } merge(knownCtx); } public void merge(CosmosDiagnosticsContext knownCtx) { if (!isMerged.compareAndSet(false, true)) { return; } CosmosDiagnosticsContext ctx = null; if (knownCtx != null) { ctx = knownCtx; } else { for (CosmosDiagnostics diagnostics : this.createdDiagnostics) { if (diagnostics.getDiagnosticsContext() != null) { ctx = diagnostics.getDiagnosticsContext(); break; } } } if (ctx == null) { return; } for (CosmosDiagnostics diagnostics : this.createdDiagnostics) { if (diagnostics.getDiagnosticsContext() == null && diagnosticsAccessor.isNotEmpty(diagnostics)) { if (this.shouldCaptureAllFeedDiagnostics && diagnosticsAccessor.getFeedResponseDiagnostics(diagnostics) != null) { AtomicBoolean isCaptured = diagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(diagnostics); if (isCaptured != null) { isCaptured.set(true); } } ctxAccessor.addDiagnostics(ctx, diagnostics); } } } public void reset() { this.createdDiagnostics.clear(); this.isMerged.set(false); } } }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private final static List<String> EMPTY_REGION_LIST = Collections.emptyList(); private final static List<URI> EMPTY_ENDPOINT_LIST = Collections.emptyList(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); private final static ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.CosmosClientTelemetryConfigAccessor telemetryCfgAccessor = ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.getCosmosClientTelemetryConfigAccessor(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsContextHelper.CosmosDiagnosticsContextAccessor ctxAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsContextHelper.getCosmosDiagnosticsContextAccessor(); private final static ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor qryOptAccessor = ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor(); private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final Map<String, Integer> clientMap = new ConcurrentHashMap<>(); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final static Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxGatewayStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private final Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private final ApiType apiType; private final CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig; private final AtomicReference<CosmosDiagnostics> mostRecentlyCreatedDiagnostics = new AtomicReference<>(null); private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; private final CosmosClientTelemetryConfig clientTelemetryConfig; private final String clientCorrelationId; private final SessionRetryOptions sessionRetryOptions; private final boolean sessionCapturingOverrideEnabled; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length == 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { assert(clientTelemetryConfig != null); Boolean clientTelemetryEnabled = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .isSendClientTelemetryToServiceEnabled(clientTelemetryConfig); assert(clientTelemetryEnabled != null); activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.clientCorrelationId = Strings.isNullOrWhiteSpace(clientCorrelationId) ? String.format("%05d",this.clientId): clientCorrelationId; clientMap.put(serviceEndpoint.toString(), clientMap.getOrDefault(serviceEndpoint.toString(), 0) + 1); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withClientMap(clientMap); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); this.cosmosEndToEndOperationLatencyPolicyConfig = cosmosEndToEndOperationLatencyPolicyConfig; this.diagnosticsClientConfig.withEndToEndOperationLatencyPolicy(cosmosEndToEndOperationLatencyPolicyConfig); this.sessionRetryOptions = sessionRetryOptions; logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withConnectionPolicy(this.connectionPolicy); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); this.diagnosticsClientConfig.withProactiveContainerInitConfig(containerProactiveInitConfig); this.diagnosticsClientConfig.withSessionRetryOptions(sessionRetryOptions); this.sessionCapturingOverrideEnabled = sessionCapturingOverrideEnabled; boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; this.clientTelemetryConfig = clientTelemetryConfig; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { CosmosDiagnostics diagnostics = diagnosticsAccessor.create(this, telemetryCfgAccessor.getSamplingRate(this.clientTelemetryConfig)); this.mostRecentlyCreatedDiagnostics.set(diagnostics); return diagnostics; } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { Throwable databaseRefreshErrorSnapshot = this.globalEndpointManager.getLatestDatabaseRefreshError(); if (databaseRefreshErrorSnapshot != null) { logger.error("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: databaseRefreshErrorSnapshot ); throw new RuntimeException("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: databaseRefreshErrorSnapshot); } else { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: } } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { (this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); (this.gatewayProxy).setCollectionCache(this.collectionCache); (this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); (this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations, this.sessionRetryOptions); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public String getClientCorrelationId() { return this.clientCorrelationId; } @Override public String getMachineId() { if (this.diagnosticsClientConfig == null) { return null; } return ClientTelemetry.getMachineId(diagnosticsClientConfig); } @Override public String getUserAgent() { return this.userAgentContainer.getUserAgent(); } @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return mostRecentlyCreatedDiagnostics.get(); } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(QueryFeedOperationState state) { return nonDocumentReadFeed(state, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return qryOptAccessor.getImpl(options).getOperationContextAndListenerTuple(); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, QueryFeedOperationState state, Class<T> klass, ResourceType resourceTypeEnum) { return createQuery(parentResourceLink, sqlQuery, state, klass, resourceTypeEnum, this); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, QueryFeedOperationState state, Class<T> klass, ResourceType resourceTypeEnum, DiagnosticsClientContext innerDiagnosticsFactory) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); CosmosQueryRequestOptions nonNullQueryOptions = state.getQueryOptions(); UUID correlationActivityIdOfRequestOptions = qryOptAccessor .getImpl(nonNullQueryOptions) .getCorrelationActivityId(); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(nonNullQueryOptions)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(nonNullQueryOptions)); final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(innerDiagnosticsFactory, false); state.registerDiagnosticsFactory( diagnosticsFactory::reset, diagnosticsFactory::merge); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( diagnosticsFactory, resourceLink, sqlQuery, state.getQueryOptions(), klass, resourceTypeEnum, queryClient, correlationActivityId, isQueryCancelledOnTimeout), invalidPartitionExceptionRetryPolicy ).flatMap(result -> { diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot()); return Mono.just(result); }) .onErrorMap(throwable -> { diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot()); return throwable; }) .doOnCancel(() -> diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot())); } private <T> Flux<FeedResponse<T>> createQueryInternal( DiagnosticsClientContext diagnosticsClientContext, String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId, final AtomicBoolean isQueryCancelledOnTimeout) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(diagnosticsClientContext, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache, isQueryCancelledOnTimeout); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; Flux<FeedResponse<T>> feedResponseFlux = iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions, resourceTypeEnum, OperationType.Query); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout( feedResponseFlux, endToEndPolicyConfig, options, isQueryCancelledOnTimeout, diagnosticsClientContext); } return feedResponseFlux; }, Queues.SMALL_BUFFER_SIZE, 1); } private static void applyExceptionToMergedDiagnosticsForQuery( CosmosQueryRequestOptions requestOptions, CosmosException exception, DiagnosticsClientContext diagnosticsClientContext) { CosmosDiagnostics mostRecentlyCreatedDiagnostics = diagnosticsClientContext.getMostRecentlyCreatedDiagnostics(); if (mostRecentlyCreatedDiagnostics != null) { BridgeInternal.setCosmosDiagnostics( exception, mostRecentlyCreatedDiagnostics); } else { List<CosmosDiagnostics> cancelledRequestDiagnostics = qryOptAccessor .getCancelledRequestDiagnosticsTracker(requestOptions); if (cancelledRequestDiagnostics != null && !cancelledRequestDiagnostics.isEmpty()) { CosmosDiagnostics aggregratedCosmosDiagnostics = cancelledRequestDiagnostics .stream() .reduce((first, toBeMerged) -> { ClientSideRequestStatistics clientSideRequestStatistics = ImplementationBridgeHelpers .CosmosDiagnosticsHelper .getCosmosDiagnosticsAccessor() .getClientSideRequestStatisticsRaw(first); ClientSideRequestStatistics toBeMergedClientSideRequestStatistics = ImplementationBridgeHelpers .CosmosDiagnosticsHelper .getCosmosDiagnosticsAccessor() .getClientSideRequestStatisticsRaw(first); if (clientSideRequestStatistics == null) { return toBeMerged; } else { clientSideRequestStatistics.mergeClientSideRequestStatistics(toBeMergedClientSideRequestStatistics); return first; } }) .get(); BridgeInternal.setCosmosDiagnostics(exception, aggregratedCosmosDiagnostics); } } } private static <T> Flux<FeedResponse<T>> getFeedResponseFluxWithTimeout( Flux<FeedResponse<T>> feedResponseFlux, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, CosmosQueryRequestOptions requestOptions, final AtomicBoolean isQueryCancelledOnTimeout, DiagnosticsClientContext diagnosticsClientContext) { Duration endToEndTimeout = endToEndPolicyConfig.getEndToEndOperationTimeout(); if (endToEndTimeout.isNegative()) { return feedResponseFlux .timeout(endToEndTimeout) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException cancellationException = getNegativeTimeoutException(null, endToEndTimeout); cancellationException.setStackTrace(throwable.getStackTrace()); isQueryCancelledOnTimeout.set(true); applyExceptionToMergedDiagnosticsForQuery( requestOptions, cancellationException, diagnosticsClientContext); return cancellationException; } return throwable; }); } return feedResponseFlux .timeout(endToEndTimeout) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); isQueryCancelledOnTimeout.set(true); applyExceptionToMergedDiagnosticsForQuery(requestOptions, exception, diagnosticsClientContext); return exception; } return throwable; }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, QueryFeedOperationState state) { return queryDatabases(new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(Paths.DATABASES_ROOT, querySpec, state, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, QueryFeedOperationState state) { return createQuery(databaseLink, new SqlQuerySpec(query), state, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if (options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null) { if (options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } if (options.getDedicatedGatewayRequestOptions().isIntegratedCacheBypassed()) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_BYPASS_CACHE, String.valueOf(options.getDedicatedGatewayRequestOptions().isIntegratedCacheBypassed())); } } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = PartitionKeyHelper.extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType, DiagnosticsClientContext clientContextOverride) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); String trackingId = null; if (options != null) { trackingId = options.getTrackingId(); } ByteBuffer content = InternalObjectNode.serializeJsonToByteBuffer(document, mapper, trackingId); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), operationType, ResourceType.Document, path, requestHeaders, options, content); if (operationType.isWriteOperation() && options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if( options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } if (options != null) { request.requestContext.setExcludeRegions(options.getExcludeRegions()); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } this.populateCapabilitiesHeader(request); if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private void populateCapabilitiesHeader(RxDocumentServiceRequest request) { if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES)) { request .getHeaders() .put(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); } } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Create, (opt, e2ecfg, clientCtxOverride) -> createDocumentCore( collectionLink, document, opt, disableAutomaticIdGeneration, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> createDocumentCore( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); if (nonNullRequestOptions.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal( collectionLink, document, nonNullRequestOptions, disableAutomaticIdGeneration, finalRetryPolicyInstance, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> createDocumentInternal( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy, DiagnosticsClientContext clientContextOverride) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create, clientContextOverride); return requestObs .flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } private static <T> Mono<T> getPointOperationResponseMonoWithE2ETimeout( RequestOptions requestOptions, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, Mono<T> rxDocumentServiceResponseMono, ScopedDiagnosticsFactory scopedDiagnosticsFactory) { requestOptions.setCosmosEndToEndLatencyPolicyConfig(endToEndPolicyConfig); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { Duration endToEndTimeout = endToEndPolicyConfig.getEndToEndOperationTimeout(); if (endToEndTimeout.isNegative()) { CosmosDiagnostics latestCosmosDiagnosticsSnapshot = scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(); if (latestCosmosDiagnosticsSnapshot == null) { scopedDiagnosticsFactory.createDiagnostics(); } return Mono.error(getNegativeTimeoutException(scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(), endToEndTimeout)); } return rxDocumentServiceResponseMono .timeout(endToEndTimeout) .onErrorMap(throwable -> getCancellationExceptionForPointOperations( scopedDiagnosticsFactory, throwable, requestOptions.getMarkE2ETimeoutInRequestContextCallbackHook())); } return rxDocumentServiceResponseMono; } private static Throwable getCancellationExceptionForPointOperations( ScopedDiagnosticsFactory scopedDiagnosticsFactory, Throwable throwable, AtomicReference<Runnable> markE2ETimeoutInRequestContextCallbackHook) { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); if (unwrappedException instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); Runnable actualCallback = markE2ETimeoutInRequestContextCallbackHook.get(); if (actualCallback != null) { logger.trace("Calling actual Mark E2E timeout callback"); actualCallback.run(); } CosmosDiagnostics lastDiagnosticsSnapshot = scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(); if (lastDiagnosticsSnapshot == null) { scopedDiagnosticsFactory.createDiagnostics(); } BridgeInternal.setCosmosDiagnostics(exception, scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics()); return exception; } return throwable; } private static CosmosException getNegativeTimeoutException(CosmosDiagnostics cosmosDiagnostics, Duration negativeTimeout) { checkNotNull(negativeTimeout, "Argument 'negativeTimeout' must not be null"); checkArgument( negativeTimeout.isNegative(), "This exception should only be used for negative timeouts"); String message = String.format("Negative timeout '%s' provided.", negativeTimeout); CosmosException exception = new OperationCancelledException(message, null); BridgeInternal.setSubStatusCode(exception, HttpConstants.SubStatusCodes.NEGATIVE_TIMEOUT_PROVIDED); if (cosmosDiagnostics != null) { BridgeInternal.setCosmosDiagnostics(exception, cosmosDiagnostics); } return exception; } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Upsert, (opt, e2ecfg, clientCtxOverride) -> upsertDocumentCore( collectionLink, document, opt, disableAutomaticIdGeneration, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> upsertDocumentCore( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); if (nonNullRequestOptions.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> upsertDocumentInternal( collectionLink, document, nonNullRequestOptions, disableAutomaticIdGeneration, finalRetryPolicyInstance, scopedDiagnosticsFactory), finalRetryPolicyInstance), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> upsertDocumentInternal( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest( retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert, clientContextOverride); return reqObs .flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Replace, (opt, e2ecfg, clientCtxOverride) -> replaceDocumentCore( documentLink, document, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> replaceDocumentCore( String documentLink, Object document, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); if (nonNullRequestOptions.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy( collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> replaceDocumentInternal( documentLink, document, nonNullRequestOptions, finalRequestRetryPolicy, endToEndPolicyConfig, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> replaceDocumentInternal( String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal( documentLink, typedDocument, options, retryPolicyInstance, clientContextOverride); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Replace, (opt, e2ecfg, clientCtxOverride) -> replaceDocumentCore( document, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> replaceDocumentCore( Document document, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(clientContextOverride); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy( collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs( () -> replaceDocumentInternal( document, options, finalRequestRetryPolicy, endToEndPolicyConfig, clientContextOverride), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal( Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal( document.getSelfLink(), document, options, retryPolicyInstance, clientContextOverride); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal( String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); if (options != null) { String trackingId = options.getTrackingId(); if (trackingId != null && !trackingId.isEmpty()) { document.set(Constants.Properties.TRACKING_ID, trackingId); } } ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs .flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } private CosmosEndToEndOperationLatencyPolicyConfig getEndToEndOperationLatencyPolicyConfig( RequestOptions options, ResourceType resourceType, OperationType operationType) { return this.getEffectiveEndToEndOperationLatencyPolicyConfig( options != null ? options.getCosmosEndToEndLatencyPolicyConfig() : null, resourceType, operationType); } private CosmosEndToEndOperationLatencyPolicyConfig getEffectiveEndToEndOperationLatencyPolicyConfig( CosmosEndToEndOperationLatencyPolicyConfig policyConfig, ResourceType resourceType, OperationType operationType) { if (policyConfig != null) { return policyConfig; } if (resourceType != ResourceType.Document) { return null; } if (!operationType.isPointOperation() && Configs.isDefaultE2ETimeoutDisabledForNonPointOperations()) { return null; } return this.cosmosEndToEndOperationLatencyPolicyConfig; } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Patch, (opt, e2ecfg, clientCtxOverride) -> patchDocumentCore( documentLink, cosmosPatchOperations, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> patchDocumentCore( String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> patchDocumentInternal( documentLink, cosmosPatchOperations, nonNullRequestOptions, documentClientRetryPolicy, scopedDiagnosticsFactory), documentClientRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> patchDocumentInternal( String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap( PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( clientContextOverride, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs .flatMap(req -> patch(request, retryPolicyInstance)) .map(resp -> toResourceResponse(resp, Document.class)); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Delete, (opt, e2ecfg, clientCtxOverride) -> deleteDocumentCore( documentLink, null, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Delete, (opt, e2ecfg, clientCtxOverride) -> deleteDocumentCore( documentLink, internalObjectNode, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> deleteDocumentCore( String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> deleteDocumentInternal( documentLink, internalObjectNode, nonNullRequestOptions, requestRetryPolicy, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> deleteDocumentInternal( String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, internalObjectNode, options, collectionObs); return requestObs .flatMap(req -> this.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { return readDocument(documentLink, options, this); } private Mono<ResourceResponse<Document>> readDocument( String documentLink, RequestOptions options, DiagnosticsClientContext innerDiagnosticsFactory) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Read, (opt, e2ecfg, clientCtxOverride) -> readDocumentCore(documentLink, opt, e2ecfg, clientCtxOverride), options, false, innerDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> readDocumentCore( String documentLink, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> readDocumentInternal( documentLink, nonNullRequestOptions, retryPolicyInstance, scopedDiagnosticsFactory), retryPolicyInstance), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> readDocumentInternal( String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Read, ResourceType.Document, path, requestHeaders, options); options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this.read(request, retryPolicyInstance) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, QueryFeedOperationState state, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", state, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, QueryFeedOperationState state, Class<T> klass) { final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(this, true); state.registerDiagnosticsFactory( () -> {}, (ctx) -> diagnosticsFactory.merge(ctx) ); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(diagnosticsFactory, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono .flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } itemIdentityList .forEach(itemIdentity -> { if (pkDefinition.getKind().equals(PartitionKind.MULTI_HASH) && ModelBridgeInternal.getPartitionKeyInternal(itemIdentity.getPartitionKey()) .getComponents().size() != pkDefinition.getPaths().size()) { throw new IllegalArgumentException(RMResources.PartitionKeyMismatch); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); Flux<FeedResponse<T>> pointReads = pointReadsForReadMany( diagnosticsFactory, partitionRangeItemKeyMap, resourceLink, state.getQueryOptions(), klass); Flux<FeedResponse<T>> queries = queryForReadMany( diagnosticsFactory, resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), state.getQueryOptions(), klass, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)); return Flux.merge(pointReads, queries) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); Collection<ClientSideRequestStatistics> aggregateRequestStatistics = new DistinctClientSideRequestStatisticsCollection(); double requestCharge = 0; for (FeedResponse<T> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults()); aggregateRequestStatistics.addAll(diagnosticsAccessor.getClientSideRequestStatistics(page.getCosmosDiagnostics())); } CosmosDiagnostics aggregatedDiagnostics = BridgeInternal.createCosmosDiagnostics(aggregatedQueryMetrics); diagnosticsAccessor.addClientSideDiagnosticsToFeed( aggregatedDiagnostics, aggregateRequestStatistics); state.mergeDiagnosticsContext(); CosmosDiagnosticsContext ctx = state.getDiagnosticsContextSnapshot(); if (ctx != null) { ctxAccessor.recordOperation( ctx, 200, 0, finalList.size(), requestCharge, aggregatedDiagnostics, null ); diagnosticsAccessor .setDiagnosticsContext( aggregatedDiagnostics, ctx); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponseWithQueryMetrics( finalList, headers, aggregatedQueryMetrics, null, false, false, aggregatedDiagnostics); return frp; }); }) .onErrorMap(throwable -> { if (throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException)throwable; CosmosDiagnostics diagnostics = cosmosException.getDiagnostics(); if (diagnostics != null) { state.mergeDiagnosticsContext(); CosmosDiagnosticsContext ctx = state.getDiagnosticsContextSnapshot(); if (ctx != null) { ctxAccessor.recordOperation( ctx, cosmosException.getStatusCode(), cosmosException.getSubStatusCode(), 0, cosmosException.getRequestCharge(), diagnostics, throwable ); diagnosticsAccessor .setDiagnosticsContext( diagnostics, state.getDiagnosticsContextSnapshot()); } } return cosmosException; } return throwable; }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); List<String> partitionKeySelectors = createPkSelectors(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; List<CosmosItemIdentity> cosmosItemIdentityList = entry.getValue(); if (cosmosItemIdentityList.size() > 1) { if (partitionKeySelectors.size() == 1 && partitionKeySelectors.get(0).equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(cosmosItemIdentityList); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelectors); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(List<CosmosItemIdentity> idPartitionKeyPairList) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec( List<CosmosItemIdentity> itemIdentities, List<String> partitionKeySelectors) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); int paramCount = 0; for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object[] pkValues = ModelBridgeInternal.getPartitionKeyInternal(pkValueAsPartitionKey).toObjectArray(); List<List<String>> partitionKeyParams = new ArrayList<>(); int pathCount = 0; for (Object pkComponentValue : pkValues) { String pkParamName = "@param" + paramCount; partitionKeyParams.add(Arrays.asList(partitionKeySelectors.get(pathCount), pkParamName)); parameters.add(new SqlParameter(pkParamName, pkComponentValue)); paramCount++; pathCount++; } String idValue = itemIdentity.getId(); String idParamName = "@param" + paramCount; paramCount++; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); for (List<String> pkParam: partitionKeyParams) { queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(pkParam.get(0)); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParam.get(1)); } queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private List<String> createPkSelectors(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.toList()); } private <T> Flux<FeedResponse<T>> queryForReadMany( ScopedDiagnosticsFactory diagnosticsFactory, String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { if (rangeQueryMap.isEmpty()) { return Flux.empty(); } UUID activityId = randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync( diagnosticsFactory, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum, isQueryCancelledOnTimeout); Flux<FeedResponse<T>> feedResponseFlux = executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions, ResourceType.Document, OperationType.Query); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout( feedResponseFlux, endToEndPolicyConfig, options, isQueryCancelledOnTimeout, diagnosticsFactory); } return feedResponseFlux; } private <T> Flux<FeedResponse<T>> pointReadsForReadMany( ScopedDiagnosticsFactory diagnosticsFactory, Map<PartitionKeyRange, List<CosmosItemIdentity>> singleItemPartitionRequestMap, String resourceLink, CosmosQueryRequestOptions queryRequestOptions, Class<T> klass) { ItemDeserializer effectiveItemDeserializer = getEffectiveItemDeserializer(queryRequestOptions, klass); return Flux.fromIterable(singleItemPartitionRequestMap.values()) .flatMap(cosmosItemIdentityList -> { if (cosmosItemIdentityList.size() == 1) { CosmosItemIdentity firstIdentity = cosmosItemIdentityList.get(0); RequestOptions requestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(queryRequestOptions); requestOptions.setPartitionKey(firstIdentity.getPartitionKey()); return this.readDocument((resourceLink + firstIdentity.getId()), requestOptions, diagnosticsFactory) .flatMap(resourceResponse -> Mono.just( new ImmutablePair<ResourceResponse<Document>, CosmosException>(resourceResponse, null) )) .onErrorResume(throwable -> { Throwable unwrappedThrowable = Exceptions.unwrap(throwable); if (unwrappedThrowable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) unwrappedThrowable; int statusCode = cosmosException.getStatusCode(); int subStatusCode = cosmosException.getSubStatusCode(); if (statusCode == HttpConstants.StatusCodes.NOTFOUND && subStatusCode == HttpConstants.SubStatusCodes.UNKNOWN) { return Mono.just(new ImmutablePair<ResourceResponse<Document>, CosmosException>(null, cosmosException)); } } return Mono.error(unwrappedThrowable); }); } return Mono.empty(); }) .flatMap(resourceResponseToExceptionPair -> { ResourceResponse<Document> resourceResponse = resourceResponseToExceptionPair.getLeft(); CosmosException cosmosException = resourceResponseToExceptionPair.getRight(); FeedResponse<T> feedResponse; if (cosmosException != null) { feedResponse = ModelBridgeInternal.createFeedResponse(new ArrayList<>(), cosmosException.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosException.getDiagnostics()))); } else { CosmosItemResponse<T> cosmosItemResponse = ModelBridgeInternal.createCosmosAsyncItemResponse(resourceResponse, klass, effectiveItemDeserializer); feedResponse = ModelBridgeInternal.createFeedResponse( Arrays.asList(cosmosItemResponse.getItem()), cosmosItemResponse.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosItemResponse.getDiagnostics()))); } return Mono.just(feedResponse); }); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, QueryFeedOperationState state, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), state, classOfT); } private <T> ItemDeserializer getEffectiveItemDeserializer( CosmosQueryRequestOptions queryRequestOptions, Class<T> klass) { Function<JsonNode, T> factoryMethod = queryRequestOptions == null ? null : qryOptAccessor.getImpl(queryRequestOptions).getItemFactoryMethod(klass); if (factoryMethod == null) { return this.itemDeserializer; } return new ItemDeserializer.JsonDeserializer(factoryMethod); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public <T> Mono<T> executeFeedOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, Supplier<DocumentClientRetryPolicy> retryPolicyFactory, RxDocumentServiceRequest req, BiFunction<Supplier<DocumentClientRetryPolicy>, RxDocumentServiceRequest, Mono<T>> feedOperation) { return RxDocumentClientImpl.this.executeFeedOperationWithAvailabilityStrategy( resourceType, operationType, retryPolicyFactory, req, feedOperation ); } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, state, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeedFromPagedFlux(DocumentCollection collection, ChangeFeedOperationState state, Class<T> classOfT) { return queryDocumentChangeFeed(collection, state.getChangeFeedOptions(), classOfT); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, QueryFeedOperationState state, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } final CosmosQueryRequestOptions effectiveOptions = qryOptAccessor.clone(state.getQueryOptions()); RequestOptions nonNullRequestOptions = qryOptAccessor.toRequestOptions(effectiveOptions); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = nonNullRequestOptions.getCosmosEndToEndLatencyPolicyConfig(); List<String> orderedApplicableRegionsForSpeculation = getApplicableRegionsForSpeculation( endToEndPolicyConfig, ResourceType.Document, OperationType.Query, false, nonNullRequestOptions); ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(this, false); if (orderedApplicableRegionsForSpeculation.size() < 2) { state.registerDiagnosticsFactory( () -> {}, (ctx) -> diagnosticsFactory.merge(ctx)); } else { state.registerDiagnosticsFactory( () -> diagnosticsFactory.reset(), (ctx) -> diagnosticsFactory.merge(ctx)); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create( diagnosticsFactory, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); List<String> partitionKeySelectors = createPkSelectors(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, partitionKeySelectors); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(state.getQueryOptions())); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); Flux<FeedResponse<T>> innerFlux = ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( diagnosticsFactory, resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId, isQueryCancelledOnTimeout); }); }, invalidPartitionExceptionRetryPolicy); if (orderedApplicableRegionsForSpeculation.size() < 2) { return innerFlux; } return innerFlux .flatMap(result -> { diagnosticsFactory.merge(nonNullRequestOptions); return Mono.just(result); }) .onErrorMap(throwable -> { diagnosticsFactory.merge(nonNullRequestOptions); return throwable; }) .doOnCancel(() -> diagnosticsFactory.merge(nonNullRequestOptions)); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, QueryFeedOperationState state) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (options != null) { request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, QueryFeedOperationState state) { return queryTriggers(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions( String collectionLink, String query, QueryFeedOperationState state) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions( String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, QueryFeedOperationState state) { return queryConflicts(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, QueryFeedOperationState state) { return queryUsers(databaseLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys( String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys( String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy(null)); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return nonDocumentReadFeed(state, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, QueryFeedOperationState state) { return queryPermissions(userLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(userLink, querySpec, state, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(QueryFeedOperationState state) { return nonDocumentReadFeed(state, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeed( QueryFeedOperationState state, ResourceType resourceType, Class<T> klass, String resourceLink) { return nonDocumentReadFeed(state.getQueryOptions(), resourceType, klass, resourceLink); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> nonDocumentReadFeedInternal(options, resourceType, klass, resourceLink, retryPolicy), retryPolicy); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeedInternal( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink, DocumentClientRetryPolicy retryPolicy) { final CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions(); Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(nonNullOptions); int maxPageSize = maxItemCount != null ? maxItemCount : -1; assert(resourceType != ResourceType.Document); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, nonNullOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> readFeed(request) .map(response -> toFeedResponsePage( response, qryOptAccessor.getImpl(nonNullOptions).getItemFactoryMethod(klass), klass)); return Paginator .getPaginatedQueryResultAsObservable( nonNullOptions, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, QueryFeedOperationState state) { return queryOffers(new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(null, querySpec, state, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } @Override public GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } @Override public AddressSelector getAddressSelector() { return new AddressSelector(this.addressResolver, this.configs.getProtocol()); } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.useGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); if (ConnectionMode.DIRECT == this.connectionPolicy.getConnectionMode()) { this.storeModel.enableThroughputControl(throughputControlStore); } else { this.gatewayProxy.enableThroughputControl(throughputControlStore); } } this.throughputControlStore.enableThroughputControlGroup(group, throughputQueryMono); } @Override public Flux<Void> submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig) { return this.storeModel.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig); } @Override public ConsistencyLevel getDefaultConsistencyLevelOfAccount() { return this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } /*** * Configure fault injector provider. * * @param injectorProvider the fault injector provider. */ @Override public void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) { checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null"); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.DIRECT) { this.storeModel.configureFaultInjectorProvider(injectorProvider, this.configs); this.addressResolver.configureFaultInjectorProvider(injectorProvider, this.configs); } this.gatewayProxy.configureFaultInjectorProvider(injectorProvider, this.configs); } @Override public void recordOpenConnectionsAndInitCachesCompleted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesCompleted(cosmosContainerIdentities); } @Override public void recordOpenConnectionsAndInitCachesStarted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesStarted(cosmosContainerIdentities); } @Override public String getMasterKeyOrResourceToken() { return this.masterKeyOrResourceToken; } private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, List<String> partitionKeySelectors) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object[] pkValues = ModelBridgeInternal.getPartitionKeyInternal(partitionKey).toObjectArray(); String pkParamNamePrefix = "@pkValue"; for (int i = 0; i < pkValues.length; i++) { StringBuilder subQueryStringBuilder = new StringBuilder(); String sqlParameterName = pkParamNamePrefix + i; if (i > 0) { subQueryStringBuilder.append(" AND "); } subQueryStringBuilder.append(" c"); subQueryStringBuilder.append(partitionKeySelectors.get(i)); subQueryStringBuilder.append((" = ")); subQueryStringBuilder.append(sqlParameterName); parameters.add(new SqlParameter(sqlParameterName, pkValues[i])); queryStringBuilder.append(subQueryStringBuilder); } return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink, boolean forceRefresh) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink, forceRefresh), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal( RxDocumentServiceRequest request, String collectionLink, boolean forceRefresh) { logger.debug("getFeedRange collectionLink=[{}] - forceRefresh={}", collectionLink, forceRefresh); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, forceRefresh, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } /** * Creates a type 4 (pseudo randomly generated) UUID. * <p> * The {@link UUID} is generated using a non-cryptographically strong pseudo random number generator. * * @return A randomly generated {@link UUID}. */ public static UUID randomUuid() { return randomUuid(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); } static UUID randomUuid(long msb, long lsb) { msb &= 0xffffffffffff0fffL; msb |= 0x0000000000004000L; lsb &= 0x3fffffffffffffffL; lsb |= 0x8000000000000000L; return new UUID(msb, lsb); } private Mono<ResourceResponse<Document>> wrapPointOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, DocumentPointOperation callback, RequestOptions initialRequestOptions, boolean idempotentWriteRetriesEnabled) { return wrapPointOperationWithAvailabilityStrategy( resourceType, operationType, callback, initialRequestOptions, idempotentWriteRetriesEnabled, this ); } private Mono<ResourceResponse<Document>> wrapPointOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, DocumentPointOperation callback, RequestOptions initialRequestOptions, boolean idempotentWriteRetriesEnabled, DiagnosticsClientContext innerDiagnosticsFactory) { checkNotNull(resourceType, "Argument 'resourceType' must not be null."); checkNotNull(operationType, "Argument 'operationType' must not be null."); checkNotNull(callback, "Argument 'callback' must not be null."); final RequestOptions nonNullRequestOptions = initialRequestOptions != null ? initialRequestOptions : new RequestOptions(); checkArgument( resourceType == ResourceType.Document, "This method can only be used for document point operations."); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(nonNullRequestOptions, resourceType, operationType); List<String> orderedApplicableRegionsForSpeculation = getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, idempotentWriteRetriesEnabled, nonNullRequestOptions); if (orderedApplicableRegionsForSpeculation.size() < 2) { return callback.apply(nonNullRequestOptions, endToEndPolicyConfig, innerDiagnosticsFactory); } ThresholdBasedAvailabilityStrategy availabilityStrategy = (ThresholdBasedAvailabilityStrategy)endToEndPolicyConfig.getAvailabilityStrategy(); List<Mono<NonTransientPointOperationResult>> monoList = new ArrayList<>(); final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(innerDiagnosticsFactory, false); orderedApplicableRegionsForSpeculation .forEach(region -> { RequestOptions clonedOptions = new RequestOptions(nonNullRequestOptions); if (monoList.isEmpty()) { Mono<NonTransientPointOperationResult> initialMonoAcrossAllRegions = callback.apply(clonedOptions, endToEndPolicyConfig, diagnosticsFactory) .map(NonTransientPointOperationResult::new) .onErrorResume( RxDocumentClientImpl::isCosmosException, t -> Mono.just( new NonTransientPointOperationResult( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); if (logger.isDebugEnabled()) { monoList.add(initialMonoAcrossAllRegions.doOnSubscribe(c -> logger.debug( "STARTING to process {} operation in region '{}'", operationType, region))); } else { monoList.add(initialMonoAcrossAllRegions); } } else { clonedOptions.setExcludeRegions( getEffectiveExcludedRegionsForHedging( nonNullRequestOptions.getExcludeRegions(), orderedApplicableRegionsForSpeculation, region) ); Mono<NonTransientPointOperationResult> regionalCrossRegionRetryMono = callback.apply(clonedOptions, endToEndPolicyConfig, diagnosticsFactory) .map(NonTransientPointOperationResult::new) .onErrorResume( RxDocumentClientImpl::isNonTransientCosmosException, t -> Mono.just( new NonTransientPointOperationResult( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); Duration delayForCrossRegionalRetry = (availabilityStrategy) .getThreshold() .plus((availabilityStrategy) .getThresholdStep() .multipliedBy(monoList.size() - 1)); if (logger.isDebugEnabled()) { monoList.add( regionalCrossRegionRetryMono .doOnSubscribe(c -> logger.debug("STARTING to process {} operation in region '{}'", operationType, region)) .delaySubscription(delayForCrossRegionalRetry)); } else { monoList.add( regionalCrossRegionRetryMono .delaySubscription(delayForCrossRegionalRetry)); } } }); return Mono .firstWithValue(monoList) .flatMap(nonTransientResult -> { diagnosticsFactory.merge(nonNullRequestOptions); if (nonTransientResult.isError()) { return Mono.error(nonTransientResult.exception); } return Mono.just(nonTransientResult.response); }) .onErrorMap(throwable -> { Throwable exception = Exceptions.unwrap(throwable); if (exception instanceof NoSuchElementException) { List<Throwable> innerThrowables = Exceptions .unwrapMultiple(exception.getCause()); int index = 0; for (Throwable innerThrowable : innerThrowables) { Throwable innerException = Exceptions.unwrap(innerThrowable); if (innerException instanceof CosmosException) { CosmosException cosmosException = Utils.as(innerException, CosmosException.class); diagnosticsFactory.merge(nonNullRequestOptions); return cosmosException; } else if (innerException instanceof NoSuchElementException) { logger.trace( "Operation in {} completed with empty result because it was cancelled.", orderedApplicableRegionsForSpeculation.get(index)); } else if (logger.isWarnEnabled()) { String message = "Unexpected Non-CosmosException when processing operation in '" + orderedApplicableRegionsForSpeculation.get(index) + "'."; logger.warn( message, innerException ); } index++; } } diagnosticsFactory.merge(nonNullRequestOptions); return exception; }) .doOnCancel(() -> diagnosticsFactory.merge(nonNullRequestOptions)); } private static boolean isCosmosException(Throwable t) { final Throwable unwrappedException = Exceptions.unwrap(t); return unwrappedException instanceof CosmosException; } private static boolean isNonTransientCosmosException(Throwable t) { final Throwable unwrappedException = Exceptions.unwrap(t); if (!(unwrappedException instanceof CosmosException)) { return false; } CosmosException cosmosException = Utils.as(unwrappedException, CosmosException.class); return isNonTransientResultForHedging( cosmosException.getStatusCode(), cosmosException.getSubStatusCode()); } private List<String> getEffectiveExcludedRegionsForHedging( List<String> initialExcludedRegions, List<String> applicableRegions, String currentRegion) { List<String> effectiveExcludedRegions = new ArrayList<>(); if (initialExcludedRegions != null) { effectiveExcludedRegions.addAll(initialExcludedRegions); } for (String applicableRegion: applicableRegions) { if (!applicableRegion.equals(currentRegion)) { effectiveExcludedRegions.add(applicableRegion); } } return effectiveExcludedRegions; } private static boolean isNonTransientResultForHedging(int statusCode, int subStatusCode) { if (statusCode < HttpConstants.StatusCodes.BADREQUEST) { return true; } if (statusCode == HttpConstants.StatusCodes.REQUEST_TIMEOUT && subStatusCode == HttpConstants.SubStatusCodes.CLIENT_OPERATION_TIMEOUT) { return true; } if (statusCode == HttpConstants.StatusCodes.BADREQUEST || statusCode == HttpConstants.StatusCodes.CONFLICT || statusCode == HttpConstants.StatusCodes.METHOD_NOT_ALLOWED || statusCode == HttpConstants.StatusCodes.PRECONDITION_FAILED || statusCode == HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE || statusCode == HttpConstants.StatusCodes.UNAUTHORIZED) { return true; } if (statusCode == HttpConstants.StatusCodes.NOTFOUND && subStatusCode == HttpConstants.SubStatusCodes.UNKNOWN) { return true; } return false; } private DiagnosticsClientContext getEffectiveClientContext(DiagnosticsClientContext clientContextOverride) { if (clientContextOverride != null) { return clientContextOverride; } return this; } /** * Returns the applicable endpoints ordered by preference list if any * @param operationType - the operationT * @return the applicable endpoints ordered by preference list if any */ private List<URI> getApplicableEndPoints(OperationType operationType, List<String> excludedRegions) { if (operationType.isReadOnlyOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableReadEndpoints(excludedRegions)); } else if (operationType.isWriteOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableWriteEndpoints(excludedRegions)); } return EMPTY_ENDPOINT_LIST; } private static List<URI> withoutNulls(List<URI> orderedEffectiveEndpointsList) { if (orderedEffectiveEndpointsList == null) { return EMPTY_ENDPOINT_LIST; } int i = 0; while (i < orderedEffectiveEndpointsList.size()) { if (orderedEffectiveEndpointsList.get(i) == null) { orderedEffectiveEndpointsList.remove(i); } else { i++; } } return orderedEffectiveEndpointsList; } private List<String> getApplicableRegionsForSpeculation( CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, ResourceType resourceType, OperationType operationType, boolean isIdempotentWriteRetriesEnabled, RequestOptions options) { return getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, isIdempotentWriteRetriesEnabled, options.getExcludeRegions()); } private List<String> getApplicableRegionsForSpeculation( CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, ResourceType resourceType, OperationType operationType, boolean isIdempotentWriteRetriesEnabled, List<String> excludedRegions) { if (endToEndPolicyConfig == null || !endToEndPolicyConfig.isEnabled()) { return EMPTY_REGION_LIST; } if (resourceType != ResourceType.Document) { return EMPTY_REGION_LIST; } if (operationType.isWriteOperation() && !isIdempotentWriteRetriesEnabled) { return EMPTY_REGION_LIST; } if (operationType.isWriteOperation() && !this.globalEndpointManager.canUseMultipleWriteLocations()) { return EMPTY_REGION_LIST; } if (!(endToEndPolicyConfig.getAvailabilityStrategy() instanceof ThresholdBasedAvailabilityStrategy)) { return EMPTY_REGION_LIST; } List<URI> endpoints = getApplicableEndPoints(operationType, excludedRegions); HashSet<String> normalizedExcludedRegions = new HashSet<>(); if (excludedRegions != null) { excludedRegions.forEach(r -> normalizedExcludedRegions.add(r.toLowerCase(Locale.ROOT))); } List<String> orderedRegionsForSpeculation = new ArrayList<>(); endpoints.forEach(uri -> { String regionName = this.globalEndpointManager.getRegionName(uri, operationType); if (!normalizedExcludedRegions.contains(regionName.toLowerCase(Locale.ROOT))) { orderedRegionsForSpeculation.add(regionName); } }); return orderedRegionsForSpeculation; } private <T> Mono<T> executeFeedOperationWithAvailabilityStrategy( final ResourceType resourceType, final OperationType operationType, final Supplier<DocumentClientRetryPolicy> retryPolicyFactory, final RxDocumentServiceRequest req, final BiFunction<Supplier<DocumentClientRetryPolicy>, RxDocumentServiceRequest, Mono<T>> feedOperation ) { checkNotNull(retryPolicyFactory, "Argument 'retryPolicyFactory' must not be null."); checkNotNull(req, "Argument 'req' must not be null."); assert(resourceType == ResourceType.Document); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = this.getEffectiveEndToEndOperationLatencyPolicyConfig( req.requestContext.getEndToEndOperationLatencyPolicyConfig(), resourceType, operationType); List<String> initialExcludedRegions = req.requestContext.getExcludeRegions(); List<String> orderedApplicableRegionsForSpeculation = this.getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, false, initialExcludedRegions ); if (orderedApplicableRegionsForSpeculation.size() < 2) { return feedOperation.apply(retryPolicyFactory, req); } ThresholdBasedAvailabilityStrategy availabilityStrategy = (ThresholdBasedAvailabilityStrategy)endToEndPolicyConfig.getAvailabilityStrategy(); List<Mono<NonTransientFeedOperationResult<T>>> monoList = new ArrayList<>(); orderedApplicableRegionsForSpeculation .forEach(region -> { RxDocumentServiceRequest clonedRequest = req.clone(); if (monoList.isEmpty()) { Mono<NonTransientFeedOperationResult<T>> initialMonoAcrossAllRegions = feedOperation.apply(retryPolicyFactory, clonedRequest) .map(NonTransientFeedOperationResult::new) .onErrorResume( RxDocumentClientImpl::isCosmosException, t -> Mono.just( new NonTransientFeedOperationResult<>( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); if (logger.isDebugEnabled()) { monoList.add(initialMonoAcrossAllRegions.doOnSubscribe(c -> logger.debug( "STARTING to process {} operation in region '{}'", operationType, region))); } else { monoList.add(initialMonoAcrossAllRegions); } } else { clonedRequest.requestContext.setExcludeRegions( getEffectiveExcludedRegionsForHedging( initialExcludedRegions, orderedApplicableRegionsForSpeculation, region) ); Mono<NonTransientFeedOperationResult<T>> regionalCrossRegionRetryMono = feedOperation.apply(retryPolicyFactory, clonedRequest) .map(NonTransientFeedOperationResult::new) .onErrorResume( RxDocumentClientImpl::isNonTransientCosmosException, t -> Mono.just( new NonTransientFeedOperationResult<>( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); Duration delayForCrossRegionalRetry = (availabilityStrategy) .getThreshold() .plus((availabilityStrategy) .getThresholdStep() .multipliedBy(monoList.size() - 1)); if (logger.isDebugEnabled()) { monoList.add( regionalCrossRegionRetryMono .doOnSubscribe(c -> logger.debug("STARTING to process {} operation in region '{}'", operationType, region)) .delaySubscription(delayForCrossRegionalRetry)); } else { monoList.add( regionalCrossRegionRetryMono .delaySubscription(delayForCrossRegionalRetry)); } } }); return Mono .firstWithValue(monoList) .flatMap(nonTransientResult -> { if (nonTransientResult.isError()) { return Mono.error(nonTransientResult.exception); } return Mono.just(nonTransientResult.response); }) .onErrorMap(throwable -> { Throwable exception = Exceptions.unwrap(throwable); if (exception instanceof NoSuchElementException) { List<Throwable> innerThrowables = Exceptions .unwrapMultiple(exception.getCause()); int index = 0; for (Throwable innerThrowable : innerThrowables) { Throwable innerException = Exceptions.unwrap(innerThrowable); if (innerException instanceof CosmosException) { return Utils.as(innerException, CosmosException.class); } else if (innerException instanceof NoSuchElementException) { logger.trace( "Operation in {} completed with empty result because it was cancelled.", orderedApplicableRegionsForSpeculation.get(index)); } else if (logger.isWarnEnabled()) { String message = "Unexpected Non-CosmosException when processing operation in '" + orderedApplicableRegionsForSpeculation.get(index) + "'."; logger.warn( message, innerException ); } index++; } } return exception; }); } @FunctionalInterface private interface DocumentPointOperation { Mono<ResourceResponse<Document>> apply(RequestOptions requestOptions, CosmosEndToEndOperationLatencyPolicyConfig endToEndOperationLatencyPolicyConfig, DiagnosticsClientContext clientContextOverride); } private static class NonTransientPointOperationResult { private final ResourceResponse<Document> response; private final CosmosException exception; public NonTransientPointOperationResult(CosmosException exception) { checkNotNull(exception, "Argument 'exception' must not be null."); this.exception = exception; this.response = null; } public NonTransientPointOperationResult(ResourceResponse<Document> response) { checkNotNull(response, "Argument 'response' must not be null."); this.exception = null; this.response = response; } public boolean isError() { return this.exception != null; } public CosmosException getException() { return this.exception; } public ResourceResponse<Document> getResponse() { return this.response; } } private static class NonTransientFeedOperationResult<T> { private final T response; private final CosmosException exception; public NonTransientFeedOperationResult(CosmosException exception) { checkNotNull(exception, "Argument 'exception' must not be null."); this.exception = exception; this.response = null; } public NonTransientFeedOperationResult(T response) { checkNotNull(response, "Argument 'response' must not be null."); this.exception = null; this.response = response; } public boolean isError() { return this.exception != null; } public CosmosException getException() { return this.exception; } public T getResponse() { return this.response; } } private static class ScopedDiagnosticsFactory implements DiagnosticsClientContext { private final AtomicBoolean isMerged = new AtomicBoolean(false); private final DiagnosticsClientContext inner; private final ConcurrentLinkedQueue<CosmosDiagnostics> createdDiagnostics; private final boolean shouldCaptureAllFeedDiagnostics; private final AtomicReference<CosmosDiagnostics> mostRecentlyCreatedDiagnostics = new AtomicReference<>(null); public ScopedDiagnosticsFactory(DiagnosticsClientContext inner, boolean shouldCaptureAllFeedDiagnostics) { checkNotNull(inner, "Argument 'inner' must not be null."); this.inner = inner; this.createdDiagnostics = new ConcurrentLinkedQueue<>(); this.shouldCaptureAllFeedDiagnostics = shouldCaptureAllFeedDiagnostics; } @Override public DiagnosticsClientConfig getConfig() { return inner.getConfig(); } @Override public CosmosDiagnostics createDiagnostics() { CosmosDiagnostics diagnostics = inner.createDiagnostics(); createdDiagnostics.add(diagnostics); mostRecentlyCreatedDiagnostics.set(diagnostics); return diagnostics; } @Override public String getUserAgent() { return inner.getUserAgent(); } @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return this.mostRecentlyCreatedDiagnostics.get(); } public void merge(RequestOptions requestOptions) { CosmosDiagnosticsContext knownCtx = null; if (requestOptions != null) { CosmosDiagnosticsContext ctxSnapshot = requestOptions.getDiagnosticsContextSnapshot(); if (ctxSnapshot != null) { knownCtx = requestOptions.getDiagnosticsContextSnapshot(); } } merge(knownCtx); } public void merge(CosmosDiagnosticsContext knownCtx) { if (!isMerged.compareAndSet(false, true)) { return; } CosmosDiagnosticsContext ctx = null; if (knownCtx != null) { ctx = knownCtx; } else { for (CosmosDiagnostics diagnostics : this.createdDiagnostics) { if (diagnostics.getDiagnosticsContext() != null) { ctx = diagnostics.getDiagnosticsContext(); break; } } } if (ctx == null) { return; } for (CosmosDiagnostics diagnostics : this.createdDiagnostics) { if (diagnostics.getDiagnosticsContext() == null && diagnosticsAccessor.isNotEmpty(diagnostics)) { if (this.shouldCaptureAllFeedDiagnostics && diagnosticsAccessor.getFeedResponseDiagnostics(diagnostics) != null) { AtomicBoolean isCaptured = diagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(diagnostics); if (isCaptured != null) { isCaptured.set(true); } } ctxAccessor.addDiagnostics(ctx, diagnostics); } } } public void reset() { this.createdDiagnostics.clear(); this.isMerged.set(false); } } }
can use getThreadInfo()
private Flux<CosmosBulkOperationResponse<TContext>> executeCore() { Integer nullableMaxConcurrentCosmosPartitions = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxConcurrentCosmosPartitions(cosmosBulkExecutionOptions); Mono<Integer> maxConcurrentCosmosPartitionsMono = nullableMaxConcurrentCosmosPartitions != null ? Mono.just(Math.max(256, nullableMaxConcurrentCosmosPartitions)) : ImplementationBridgeHelpers .CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getFeedRanges(this.container, false).map(ranges -> Math.max(256, ranges.size() * 2)); return maxConcurrentCosmosPartitionsMono .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMapMany(maxConcurrentCosmosPartitions -> { logDebugOrWarning("BulkExecutor.execute with MaxConcurrentPartitions: {}, Context: {}", maxConcurrentCosmosPartitions, this.operationContextText); return this.inputOperations .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .onErrorMap(throwable -> { logger.error("{}: Skipping an error operation while processing. Cause: {}, Context: {}", Thread.currentThread ().getName(), throwable.getMessage(), this.operationContextText, throwable); return throwable; }) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } logger.trace( "SetupRetryPolicy, {}, TotalCount: {}, Context: {}, {}", getItemOperationDiagnostics(cosmosItemOperation), totalCount.get(), this.operationContextText, getThreadInfo() ); }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logDebugOrWarning("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.cancelFlushTask(true); this.onFlush(); logDebugOrWarning("Scheduled new flush operation {}, Context: {}", getThreadInfo(), this.operationContextText); } }) .mergeWith(mainSink.asFlux()) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap( operation -> { logger.trace("Before Resolve PkRangeId, {}, Context: {} {}", getItemOperationDiagnostics(operation), this.operationContextText, getThreadInfo()); return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); logger.trace("Resolved PkRangeId, {}, PKRangeId: {} Context: {} {}", getItemOperationDiagnostics(operation), pkRangeId, this.operationContextText, getThreadInfo()); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap( this::executePartitionedGroup, maxConcurrentCosmosPartitions) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logDebugOrWarning("All work completed, {}, TotalCount: {}, Context: {} {}", getItemOperationDiagnostics(requestAndResponse.getOperation()), totalCountAfterDecrement, this.operationContextText, getThreadInfo()); completeAllSinks(); } else { if (totalCountAfterDecrement == 0) { logDebugOrWarning( "No Work left - but mainSource not yet completed, Context: {} {}", this.operationContextText, getThreadInfo()); } logger.trace( "Work left - TotalCount after decrement: {}, main sink completed {}, {}, Context: {} {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, getItemOperationDiagnostics(requestAndResponse.getOperation()), this.operationContextText, getThreadInfo()); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logDebugOrWarning("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logDebugOrWarning( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {} {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText, getThreadInfo()); } }); }); }
Thread.currentThread ().getName(),
default concurrency (256), Integer nullableMaxConcurrentCosmosPartitions = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxConcurrentCosmosPartitions(cosmosBulkExecutionOptions); Mono<Integer> maxConcurrentCosmosPartitionsMono = nullableMaxConcurrentCosmosPartitions != null ? Mono.just(Math.max(256, nullableMaxConcurrentCosmosPartitions)) : ImplementationBridgeHelpers .CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getFeedRanges(this.container, false).map(ranges -> Math.max(256, ranges.size() * 2)); return maxConcurrentCosmosPartitionsMono .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMapMany(maxConcurrentCosmosPartitions -> { logDebugOrWarning("BulkExecutor.execute with MaxConcurrentPartitions: {}, Context: {}", maxConcurrentCosmosPartitions, this.operationContextText); return this.inputOperations .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .onErrorMap(throwable -> { logger.error("{}: Skipping an error operation while processing. Cause: {}, Context: {}", getThreadInfo(), throwable.getMessage(), this.operationContextText, throwable); return throwable; }) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } logger.trace( "SetupRetryPolicy, {}, TotalCount: {}, Context: {}, {}", getItemOperationDiagnostics(cosmosItemOperation), totalCount.get(), this.operationContextText, getThreadInfo() ); }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logDebugOrWarning("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.cancelFlushTask(true); this.onFlush(); logDebugOrWarning("Scheduled new flush operation {}, Context: {}", getThreadInfo(), this.operationContextText); } }) .mergeWith(mainSink.asFlux()) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap( operation -> { logger.trace("Before Resolve PkRangeId, {}, Context: {} {}", getItemOperationDiagnostics(operation), this.operationContextText, getThreadInfo()); return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); logger.trace("Resolved PkRangeId, {}, PKRangeId: {} Context: {} {}", getItemOperationDiagnostics(operation), pkRangeId, this.operationContextText, getThreadInfo()); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap( this::executePartitionedGroup, maxConcurrentCosmosPartitions) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logDebugOrWarning("All work completed, {}, TotalCount: {}, Context: {} {}", getItemOperationDiagnostics(requestAndResponse.getOperation()), totalCountAfterDecrement, this.operationContextText, getThreadInfo()); completeAllSinks(); } else { if (totalCountAfterDecrement == 0) { logDebugOrWarning( "No Work left - but mainSource not yet completed, Context: {} {}", this.operationContextText, getThreadInfo()); } logger.trace( "Work left - TotalCount after decrement: {}, main sink completed {}, {}, Context: {} {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, getItemOperationDiagnostics(requestAndResponse.getOperation()), this.operationContextText, getThreadInfo()); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logDebugOrWarning("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logDebugOrWarning( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {} {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText, getThreadInfo()); } }); }
class BulkExecutor<TContext> implements Disposable { private final static ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper.CosmosBulkExecutionOptionsAccessor bulkOptionsAccessor = ImplementationBridgeHelpers .CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor(); private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private static final ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor clientAccessor = ImplementationBridgeHelpers.CosmosAsyncClientHelper.getCosmosAsyncClientAccessor(); private final CosmosAsyncContainer container; private final int maxMicroBatchPayloadSizeInBytes; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicBoolean isDisposed = new AtomicBoolean(false); private final AtomicBoolean isShutdown = new AtomicBoolean(false); private final AtomicInteger totalCount; private final static Sinks.EmitFailureHandler serializedEmitFailureHandler = new SerializedEmitFailureHandler(); private final static Sinks.EmitFailureHandler serializedCompleteEmitFailureHandler = new SerializedCompleteEmitFailureHandler();; private final Sinks.Many<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final CosmosAsyncClient cosmosClient; private final String bulkSpanName; private final AtomicReference<Disposable> scheduledFutureForFlush; private final String identifier = "BulkExecutor-" + instanceCount.incrementAndGet(); private final BulkExecutorDiagnosticsTracker diagnosticsTracker; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.maxMicroBatchPayloadSizeInBytes = bulkOptionsAccessor .getMaxMicroBatchPayloadSizeInBytes(cosmosBulkOptions); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.bulkSpanName = "nonTransactionalBatch." + this.container.getId(); this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.cosmosClient = ImplementationBridgeHelpers .CosmosAsyncDatabaseHelper .getCosmosAsyncDatabaseAccessor() .getCosmosAsyncClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = bulkOptionsAccessor .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = bulkOptionsAccessor .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = bulkOptionsAccessor .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = identifier + "[" + operationListener.getOperationContext().toString() + "]"; } else { operationContextText = identifier +"[n/a]"; } this.diagnosticsTracker = bulkOptionsAccessor.getDiagnosticsTracker(cosmosBulkOptions); mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainSink = Sinks.many().unicast().onBackpressureBuffer(); groupSinks = new CopyOnWriteArrayList<>(); this.scheduledFutureForFlush = new AtomicReference<>(CosmosSchedulers .BULK_EXECUTOR_FLUSH_BOUNDED_ELASTIC .schedulePeriodically( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS)); logger.debug("Instantiated BulkExecutor, Context: {}", this.operationContextText); } @Override public void dispose() { if (this.isDisposed.compareAndSet(false, true)) { long totalCountSnapshot = totalCount.get(); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.shutdown(); } } } @Override public boolean isDisposed() { return this.isDisposed.get(); } private void cancelFlushTask(boolean initializeAggressiveFlush) { long flushIntervalAfterDrainingIncomingFlux = Math.min( this.maxMicroBatchIntervalInMs, BatchRequestResponseConstants .DEFAULT_MAX_MICRO_BATCH_INTERVAL_AFTER_DRAINING_INCOMING_FLUX_IN_MILLISECONDS); Disposable newFlushTask = initializeAggressiveFlush ? CosmosSchedulers .BULK_EXECUTOR_FLUSH_BOUNDED_ELASTIC .schedulePeriodically( this::onFlush, flushIntervalAfterDrainingIncomingFlux, flushIntervalAfterDrainingIncomingFlux, TimeUnit.MILLISECONDS) : null; Disposable scheduledFutureSnapshot = this.scheduledFutureForFlush.getAndSet(newFlushTask); if (scheduledFutureSnapshot != null) { try { scheduledFutureSnapshot.dispose(); logDebugOrWarning("Cancelled all future scheduled tasks {}, Context: {}", getThreadInfo(), this.operationContextText); } catch (Exception e) { logger.warn("Failed to cancel scheduled tasks{}, Context: {}", getThreadInfo(), this.operationContextText, e); } } } private void logInfoOrWarning(String msg, Object... args) { if (this.diagnosticsTracker == null || !this.diagnosticsTracker.verboseLoggingAfterReEnqueueingRetriesEnabled()) { logger.info(msg, args); } else { logger.warn(msg, args); } } private void logDebugOrWarning(String msg, Object... args) { if (this.diagnosticsTracker == null || !this.diagnosticsTracker.verboseLoggingAfterReEnqueueingRetriesEnabled()) { logger.debug(msg, args); } else { logger.warn(msg, args); } } private void shutdown() { if (this.isShutdown.compareAndSet(false, true)) { logDebugOrWarning("Shutting down, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); this.cancelFlushTask(false); } } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this .executeCore() .doFinally((SignalType signal) -> { if (signal == SignalType.ON_COMPLETE) { logDebugOrWarning("BulkExecutor.execute flux completed - this.totalCount.get(), this.operationContextText, getThreadInfo()); } else { int itemsLeftSnapshot = this.totalCount.get(); if (itemsLeftSnapshot > 0) { logInfoOrWarning("BulkExecutor.execute flux terminated - Signal: {} - signal, itemsLeftSnapshot, this.operationContextText, getThreadInfo()); } else { logDebugOrWarning("BulkExecutor.execute flux terminated - Signal: {} - signal, itemsLeftSnapshot, this.operationContextText, getThreadInfo()); } } this.dispose(); }); } private Flux<CosmosBulkOperationResponse<TContext>> executeCore() { } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); AtomicInteger currentTotalSerializedLength = new AtomicInteger(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); logger.trace( "BufferUntil - enqueued {}, {}, Context: {} {}", timestamp, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (itemOperation == FlushBuffersItemOperation.singleton()) { long currentMicroBatchSizeSnapshot = currentMicroBatchSize.get(); if (currentMicroBatchSizeSnapshot > 0) { logger.trace( "Flushing PKRange {} (batch size: {}) due to FlushItemOperation, Context: {} {}", thresholds.getPartitionKeyRangeId(), currentMicroBatchSizeSnapshot, this.operationContextText, getThreadInfo()); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); currentTotalSerializedLength.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); int totalSerializedLength = this.calculateTotalSerializedLength(currentTotalSerializedLength, itemOperation); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs || totalSerializedLength >= this.maxMicroBatchPayloadSizeInBytes) { logDebugOrWarning( "BufferUntil - Flushing PKRange {} due to BatchSize ({}), payload size ({}) or age ({}), " + "Triggering {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), batchSize, totalSerializedLength, age, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); currentTotalSerializedLength.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } logDebugOrWarning( "Flushing PKRange {} micro batch with {} operations, Context: {} {}", thresholds.getPartitionKeyRangeId(), operations.size(), this.operationContextText, getThreadInfo()); return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private int calculateTotalSerializedLength(AtomicInteger currentTotalSerializedLength, CosmosItemOperation item) { if (item instanceof CosmosItemOperationBase) { return currentTotalSerializedLength.accumulateAndGet( ((CosmosItemOperationBase) item).getSerializedLength(), Integer::sum); } return currentTotalSerializedLength.get(); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.trace("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange, this.maxMicroBatchPayloadSizeInBytes); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMapMany(response -> { if (diagnosticsTracker != null && response.getDiagnostics() != null) { diagnosticsTracker.trackDiagnostics(response.getDiagnostics().getDiagnosticsContext()); } return Flux .fromIterable(response.getResults()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds)); }) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux .fromIterable(serverRequest.getOperations()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal .createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); logDebugOrWarning( "HandleTransactionalBatchOperationResult - PKRange {}, Response Status Code {}, " + "Operation Status Code, {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { logDebugOrWarning( "HandleTransactionalBatchOperationResult - enqueue retry, PKRange {}, Response " + "Status Code {}, Operation Status Code, {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { if (response.getStatusCode() == HttpConstants.StatusCodes.CONFLICT || response.getStatusCode() == HttpConstants.StatusCodes.PRECONDITION_FAILED) { logDebugOrWarning( "HandleTransactionalBatchOperationResult - Fail, PKRange {}, Response Status " + "Code {}, Operation Status Code {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); } else { logger.error( "HandleTransactionalBatchOperationResult - Fail, PKRange {}, Response Status " + "Code {}, Operation Status Code {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); } return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { logDebugOrWarning( "HandleTransactionalBatchExecutionException, PKRange {}, Error: {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode(), itemBulkOperation, cosmosException) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { logDebugOrWarning( "HandleTransactionalBatchExecutionException - Retry due to split, PKRange {}, Error: " + "{}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); mainSink.emitNext(itemOperation, serializedEmitFailureHandler); return Mono.empty(); } else { logDebugOrWarning( "HandleTransactionalBatchExecutionException - Retry other, PKRange {}, Error: " + "{}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setThroughputControlGroupName(cosmosBulkExecutionOptions.getThroughputControlGroupName()); options.setExcludeRegions(cosmosBulkExecutionOptions.getExcludedRegions()); Map<String, String> customOptions = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getCustomOptions(cosmosBulkExecutionOptions); if (customOptions != null && !customOptions.isEmpty()) { for(Map.Entry<String, String> entry : customOptions.entrySet()) { options.setHeader(entry.getKey(), entry.getValue()); } } options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getOperationType() == CosmosItemOperationType.READ || (itemBulkOperation.getRequestOptions() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled())) { options.setContentResponseOnWriteEnabled(true); break; } } } } return withContext(context -> { final Mono<CosmosBatchResponse> responseMono = this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); return clientAccessor.getDiagnosticsProvider(this.cosmosClient) .traceEnabledBatchResponsePublisher( responseMono, context, this.bulkSpanName, this.container.getDatabase().getId(), this.container.getId(), this.cosmosClient, options.getConsistencyLevel(), OperationType.Batch, ResourceType.Document, options); }); } private void completeAllSinks() { logInfoOrWarning("Closing all sinks, Context: {}", this.operationContextText); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.emitComplete(serializedCompleteEmitFailureHandler); this.shutdown(); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed. Context: {}", this.operationContextText, t); } } private static String getItemOperationDiagnostics(CosmosItemOperation operation) { if (operation == FlushBuffersItemOperation.singleton()) { return "ItemOperation[Type: Flush]"; } return "ItemOperation[Type: " + operation.getOperationType().toString() + ", PK: " + (operation.getPartitionKeyValue() != null ? operation.getPartitionKeyValue().toString() : "n/a") + ", id: " + operation.getId() + "]"; } private static String getThreadInfo() { StringBuilder sb = new StringBuilder(); Thread t = Thread.currentThread(); sb .append("Thread[") .append("Name: ") .append(t.getName()) .append(",Group: ") .append(t.getThreadGroup() != null ? t.getThreadGroup().getName() : "n/a") .append(", isDaemon: ") .append(t.isDaemon()) .append(", Id: ") .append(t.getId()) .append("]"); return sb.toString(); } private static class SerializedEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } logger.error("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; } } private static class SerializedCompleteEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } if (emitResult == Sinks.EmitResult.FAIL_CANCELLED || emitResult == Sinks.EmitResult.FAIL_TERMINATED) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Main sink already completed, Signal:{}, Result: {}", signalType, emitResult); return false; } logger.error("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; } } }
class BulkExecutor<TContext> implements Disposable { private final static ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper.CosmosBulkExecutionOptionsAccessor bulkOptionsAccessor = ImplementationBridgeHelpers .CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor(); private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private static final ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor clientAccessor = ImplementationBridgeHelpers.CosmosAsyncClientHelper.getCosmosAsyncClientAccessor(); private final CosmosAsyncContainer container; private final int maxMicroBatchPayloadSizeInBytes; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicBoolean isDisposed = new AtomicBoolean(false); private final AtomicBoolean isShutdown = new AtomicBoolean(false); private final AtomicInteger totalCount; private final static Sinks.EmitFailureHandler serializedEmitFailureHandler = new SerializedEmitFailureHandler(); private final static Sinks.EmitFailureHandler serializedCompleteEmitFailureHandler = new SerializedCompleteEmitFailureHandler();; private final Sinks.Many<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final CosmosAsyncClient cosmosClient; private final String bulkSpanName; private final AtomicReference<Disposable> scheduledFutureForFlush; private final String identifier = "BulkExecutor-" + instanceCount.incrementAndGet(); private final BulkExecutorDiagnosticsTracker diagnosticsTracker; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.maxMicroBatchPayloadSizeInBytes = bulkOptionsAccessor .getMaxMicroBatchPayloadSizeInBytes(cosmosBulkOptions); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.bulkSpanName = "nonTransactionalBatch." + this.container.getId(); this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.cosmosClient = ImplementationBridgeHelpers .CosmosAsyncDatabaseHelper .getCosmosAsyncDatabaseAccessor() .getCosmosAsyncClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = bulkOptionsAccessor .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = bulkOptionsAccessor .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = bulkOptionsAccessor .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = identifier + "[" + operationListener.getOperationContext().toString() + "]"; } else { operationContextText = identifier +"[n/a]"; } this.diagnosticsTracker = bulkOptionsAccessor.getDiagnosticsTracker(cosmosBulkOptions); mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainSink = Sinks.many().unicast().onBackpressureBuffer(); groupSinks = new CopyOnWriteArrayList<>(); this.scheduledFutureForFlush = new AtomicReference<>(CosmosSchedulers .BULK_EXECUTOR_FLUSH_BOUNDED_ELASTIC .schedulePeriodically( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS)); logger.debug("Instantiated BulkExecutor, Context: {}", this.operationContextText); } @Override public void dispose() { if (this.isDisposed.compareAndSet(false, true)) { long totalCountSnapshot = totalCount.get(); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.shutdown(); } } } @Override public boolean isDisposed() { return this.isDisposed.get(); } private void cancelFlushTask(boolean initializeAggressiveFlush) { long flushIntervalAfterDrainingIncomingFlux = Math.min( this.maxMicroBatchIntervalInMs, BatchRequestResponseConstants .DEFAULT_MAX_MICRO_BATCH_INTERVAL_AFTER_DRAINING_INCOMING_FLUX_IN_MILLISECONDS); Disposable newFlushTask = initializeAggressiveFlush ? CosmosSchedulers .BULK_EXECUTOR_FLUSH_BOUNDED_ELASTIC .schedulePeriodically( this::onFlush, flushIntervalAfterDrainingIncomingFlux, flushIntervalAfterDrainingIncomingFlux, TimeUnit.MILLISECONDS) : null; Disposable scheduledFutureSnapshot = this.scheduledFutureForFlush.getAndSet(newFlushTask); if (scheduledFutureSnapshot != null) { try { scheduledFutureSnapshot.dispose(); logDebugOrWarning("Cancelled all future scheduled tasks {}, Context: {}", getThreadInfo(), this.operationContextText); } catch (Exception e) { logger.warn("Failed to cancel scheduled tasks{}, Context: {}", getThreadInfo(), this.operationContextText, e); } } } private void logInfoOrWarning(String msg, Object... args) { if (this.diagnosticsTracker == null || !this.diagnosticsTracker.verboseLoggingAfterReEnqueueingRetriesEnabled()) { logger.info(msg, args); } else { logger.warn(msg, args); } } private void logDebugOrWarning(String msg, Object... args) { if (this.diagnosticsTracker == null || !this.diagnosticsTracker.verboseLoggingAfterReEnqueueingRetriesEnabled()) { logger.debug(msg, args); } else { logger.warn(msg, args); } } private void shutdown() { if (this.isShutdown.compareAndSet(false, true)) { logDebugOrWarning("Shutting down, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); this.cancelFlushTask(false); } } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this .executeCore() .doFinally((SignalType signal) -> { if (signal == SignalType.ON_COMPLETE) { logDebugOrWarning("BulkExecutor.execute flux completed - this.totalCount.get(), this.operationContextText, getThreadInfo()); } else { int itemsLeftSnapshot = this.totalCount.get(); if (itemsLeftSnapshot > 0) { logInfoOrWarning("BulkExecutor.execute flux terminated - Signal: {} - signal, itemsLeftSnapshot, this.operationContextText, getThreadInfo()); } else { logDebugOrWarning("BulkExecutor.execute flux terminated - Signal: {} - signal, itemsLeftSnapshot, this.operationContextText, getThreadInfo()); } } this.dispose(); }); } private Flux<CosmosBulkOperationResponse<TContext>> executeCore() { } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); AtomicInteger currentTotalSerializedLength = new AtomicInteger(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); logger.trace( "BufferUntil - enqueued {}, {}, Context: {} {}", timestamp, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (itemOperation == FlushBuffersItemOperation.singleton()) { long currentMicroBatchSizeSnapshot = currentMicroBatchSize.get(); if (currentMicroBatchSizeSnapshot > 0) { logger.trace( "Flushing PKRange {} (batch size: {}) due to FlushItemOperation, Context: {} {}", thresholds.getPartitionKeyRangeId(), currentMicroBatchSizeSnapshot, this.operationContextText, getThreadInfo()); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); currentTotalSerializedLength.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); int totalSerializedLength = this.calculateTotalSerializedLength(currentTotalSerializedLength, itemOperation); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs || totalSerializedLength >= this.maxMicroBatchPayloadSizeInBytes) { logDebugOrWarning( "BufferUntil - Flushing PKRange {} due to BatchSize ({}), payload size ({}) or age ({}), " + "Triggering {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), batchSize, totalSerializedLength, age, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); currentTotalSerializedLength.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } logDebugOrWarning( "Flushing PKRange {} micro batch with {} operations, Context: {} {}", thresholds.getPartitionKeyRangeId(), operations.size(), this.operationContextText, getThreadInfo()); return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private int calculateTotalSerializedLength(AtomicInteger currentTotalSerializedLength, CosmosItemOperation item) { if (item instanceof CosmosItemOperationBase) { return currentTotalSerializedLength.accumulateAndGet( ((CosmosItemOperationBase) item).getSerializedLength(), Integer::sum); } return currentTotalSerializedLength.get(); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.trace("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange, this.maxMicroBatchPayloadSizeInBytes); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMapMany(response -> { if (diagnosticsTracker != null && response.getDiagnostics() != null) { diagnosticsTracker.trackDiagnostics(response.getDiagnostics().getDiagnosticsContext()); } return Flux .fromIterable(response.getResults()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds)); }) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux .fromIterable(serverRequest.getOperations()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal .createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); logDebugOrWarning( "HandleTransactionalBatchOperationResult - PKRange {}, Response Status Code {}, " + "Operation Status Code, {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { logDebugOrWarning( "HandleTransactionalBatchOperationResult - enqueue retry, PKRange {}, Response " + "Status Code {}, Operation Status Code, {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { if (response.getStatusCode() == HttpConstants.StatusCodes.CONFLICT || response.getStatusCode() == HttpConstants.StatusCodes.PRECONDITION_FAILED) { logDebugOrWarning( "HandleTransactionalBatchOperationResult - Fail, PKRange {}, Response Status " + "Code {}, Operation Status Code {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); } else { logger.error( "HandleTransactionalBatchOperationResult - Fail, PKRange {}, Response Status " + "Code {}, Operation Status Code {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); } return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { logDebugOrWarning( "HandleTransactionalBatchExecutionException, PKRange {}, Error: {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode(), itemBulkOperation, cosmosException) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { logDebugOrWarning( "HandleTransactionalBatchExecutionException - Retry due to split, PKRange {}, Error: " + "{}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); mainSink.emitNext(itemOperation, serializedEmitFailureHandler); return Mono.empty(); } else { logDebugOrWarning( "HandleTransactionalBatchExecutionException - Retry other, PKRange {}, Error: " + "{}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setThroughputControlGroupName(cosmosBulkExecutionOptions.getThroughputControlGroupName()); options.setExcludeRegions(cosmosBulkExecutionOptions.getExcludedRegions()); Map<String, String> customOptions = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getCustomOptions(cosmosBulkExecutionOptions); if (customOptions != null && !customOptions.isEmpty()) { for(Map.Entry<String, String> entry : customOptions.entrySet()) { options.setHeader(entry.getKey(), entry.getValue()); } } options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getOperationType() == CosmosItemOperationType.READ || (itemBulkOperation.getRequestOptions() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled())) { options.setContentResponseOnWriteEnabled(true); break; } } } } return withContext(context -> { final Mono<CosmosBatchResponse> responseMono = this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); return clientAccessor.getDiagnosticsProvider(this.cosmosClient) .traceEnabledBatchResponsePublisher( responseMono, context, this.bulkSpanName, this.container.getDatabase().getId(), this.container.getId(), this.cosmosClient, options.getConsistencyLevel(), OperationType.Batch, ResourceType.Document, options); }); } private void completeAllSinks() { logInfoOrWarning("Closing all sinks, Context: {}", this.operationContextText); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.emitComplete(serializedCompleteEmitFailureHandler); this.shutdown(); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed. Context: {}", this.operationContextText, t); } } private static String getItemOperationDiagnostics(CosmosItemOperation operation) { if (operation == FlushBuffersItemOperation.singleton()) { return "ItemOperation[Type: Flush]"; } return "ItemOperation[Type: " + operation.getOperationType().toString() + ", PK: " + (operation.getPartitionKeyValue() != null ? operation.getPartitionKeyValue().toString() : "n/a") + ", id: " + operation.getId() + "]"; } private static String getThreadInfo() { StringBuilder sb = new StringBuilder(); Thread t = Thread.currentThread(); sb .append("Thread[") .append("Name: ") .append(t.getName()) .append(",Group: ") .append(t.getThreadGroup() != null ? t.getThreadGroup().getName() : "n/a") .append(", isDaemon: ") .append(t.isDaemon()) .append(", Id: ") .append(t.getId()) .append("]"); return sb.toString(); } private static class SerializedEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } logger.error("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; } } private static class SerializedCompleteEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } if (emitResult == Sinks.EmitResult.FAIL_CANCELLED || emitResult == Sinks.EmitResult.FAIL_TERMINATED) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Main sink already completed, Signal:{}, Result: {}", signalType, emitResult); return false; } logger.error("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; } } }
info or warning?
public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } if (emitResult == Sinks.EmitResult.FAIL_CANCELLED || emitResult == Sinks.EmitResult.FAIL_TERMINATED) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Main sink already completed, Signal:{}, Result: {}", signalType, emitResult); return false; } logger.error("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; }
logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Main sink already completed, Signal:{}, Result: {}", signalType, emitResult);
public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } logger.error("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; }
class SerializedEmitFailureHandler implements Sinks.EmitFailureHandler { @Override }
class SerializedEmitFailureHandler implements Sinks.EmitFailureHandler { @Override }
I want the vmId - in the c logs with Warn there was nowhere the vmId emitted
public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry( this, null, randomUuid().toString(), ManagementFactory.getRuntimeMXBean().getName(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.configs, this.clientTelemetryConfig, this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init().thenEmpty((publisher) -> { logger.warn( "Initialized DocumentClient [{}] with machineId[{}]" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}]", clientId, ClientTelemetry.getMachineId(diagnosticsClientConfig), serviceEndpoint, connectionPolicy, consistencyLevel); }).subscribe(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); ConsistencyLevel effectiveConsistencyLevel = consistencyLevel != null ? consistencyLevel : this.getDefaultConsistencyLevelOfAccount(); boolean updatedDisableSessionCapturing = (ConsistencyLevel.SESSION != effectiveConsistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer.setDisableSessionCapturing(updatedDisableSessionCapturing); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } }
logger.warn(
public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry( this, null, randomUuid().toString(), ManagementFactory.getRuntimeMXBean().getName(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.configs, this.clientTelemetryConfig, this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init().thenEmpty((publisher) -> { logger.warn( "Initialized DocumentClient [{}] with machineId[{}]" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}]", clientId, ClientTelemetry.getMachineId(diagnosticsClientConfig), serviceEndpoint, connectionPolicy, consistencyLevel); }).subscribe(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); ConsistencyLevel effectiveConsistencyLevel = consistencyLevel != null ? consistencyLevel : this.getDefaultConsistencyLevelOfAccount(); boolean updatedDisableSessionCapturing = (ConsistencyLevel.SESSION != effectiveConsistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer.setDisableSessionCapturing(updatedDisableSessionCapturing); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private final static List<String> EMPTY_REGION_LIST = Collections.emptyList(); private final static List<URI> EMPTY_ENDPOINT_LIST = Collections.emptyList(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); private final static ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.CosmosClientTelemetryConfigAccessor telemetryCfgAccessor = ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.getCosmosClientTelemetryConfigAccessor(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsContextHelper.CosmosDiagnosticsContextAccessor ctxAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsContextHelper.getCosmosDiagnosticsContextAccessor(); private final static ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor qryOptAccessor = ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor(); private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final Map<String, Integer> clientMap = new ConcurrentHashMap<>(); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final static Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxGatewayStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private final Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private final ApiType apiType; private final CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig; private final AtomicReference<CosmosDiagnostics> mostRecentlyCreatedDiagnostics = new AtomicReference<>(null); private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; private final CosmosClientTelemetryConfig clientTelemetryConfig; private final String clientCorrelationId; private final SessionRetryOptions sessionRetryOptions; private final boolean sessionCapturingOverrideEnabled; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length == 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { assert(clientTelemetryConfig != null); Boolean clientTelemetryEnabled = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .isSendClientTelemetryToServiceEnabled(clientTelemetryConfig); assert(clientTelemetryEnabled != null); activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.clientCorrelationId = Strings.isNullOrWhiteSpace(clientCorrelationId) ? String.format("%05d",this.clientId): clientCorrelationId; clientMap.put(serviceEndpoint.toString(), clientMap.getOrDefault(serviceEndpoint.toString(), 0) + 1); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withClientMap(clientMap); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); this.cosmosEndToEndOperationLatencyPolicyConfig = cosmosEndToEndOperationLatencyPolicyConfig; this.diagnosticsClientConfig.withEndToEndOperationLatencyPolicy(cosmosEndToEndOperationLatencyPolicyConfig); this.sessionRetryOptions = sessionRetryOptions; logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withConnectionPolicy(this.connectionPolicy); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); this.diagnosticsClientConfig.withProactiveContainerInitConfig(containerProactiveInitConfig); this.diagnosticsClientConfig.withSessionRetryOptions(sessionRetryOptions); this.sessionCapturingOverrideEnabled = sessionCapturingOverrideEnabled; boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; this.clientTelemetryConfig = clientTelemetryConfig; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { CosmosDiagnostics diagnostics = diagnosticsAccessor.create(this, telemetryCfgAccessor.getSamplingRate(this.clientTelemetryConfig)); this.mostRecentlyCreatedDiagnostics.set(diagnostics); return diagnostics; } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { Throwable databaseRefreshErrorSnapshot = this.globalEndpointManager.getLatestDatabaseRefreshError(); if (databaseRefreshErrorSnapshot != null) { logger.error("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: databaseRefreshErrorSnapshot ); throw new RuntimeException("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: databaseRefreshErrorSnapshot); } else { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: } } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { (this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); (this.gatewayProxy).setCollectionCache(this.collectionCache); (this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); (this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations, this.sessionRetryOptions); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public String getClientCorrelationId() { return this.clientCorrelationId; } @Override public String getMachineId() { if (this.diagnosticsClientConfig == null) { return null; } return ClientTelemetry.getMachineId(diagnosticsClientConfig); } @Override public String getUserAgent() { return this.userAgentContainer.getUserAgent(); } @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return mostRecentlyCreatedDiagnostics.get(); } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(QueryFeedOperationState state) { return nonDocumentReadFeed(state, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return qryOptAccessor.getImpl(options).getOperationContextAndListenerTuple(); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, QueryFeedOperationState state, Class<T> klass, ResourceType resourceTypeEnum) { return createQuery(parentResourceLink, sqlQuery, state, klass, resourceTypeEnum, this); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, QueryFeedOperationState state, Class<T> klass, ResourceType resourceTypeEnum, DiagnosticsClientContext innerDiagnosticsFactory) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); CosmosQueryRequestOptions nonNullQueryOptions = state.getQueryOptions(); UUID correlationActivityIdOfRequestOptions = qryOptAccessor .getImpl(nonNullQueryOptions) .getCorrelationActivityId(); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(nonNullQueryOptions)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(nonNullQueryOptions)); final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(innerDiagnosticsFactory, false); state.registerDiagnosticsFactory( diagnosticsFactory::reset, diagnosticsFactory::merge); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( diagnosticsFactory, resourceLink, sqlQuery, state.getQueryOptions(), klass, resourceTypeEnum, queryClient, correlationActivityId, isQueryCancelledOnTimeout), invalidPartitionExceptionRetryPolicy ).flatMap(result -> { diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot()); return Mono.just(result); }) .onErrorMap(throwable -> { diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot()); return throwable; }) .doOnCancel(() -> diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot())); } private <T> Flux<FeedResponse<T>> createQueryInternal( DiagnosticsClientContext diagnosticsClientContext, String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId, final AtomicBoolean isQueryCancelledOnTimeout) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(diagnosticsClientContext, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache, isQueryCancelledOnTimeout); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; Flux<FeedResponse<T>> feedResponseFlux = iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions, resourceTypeEnum, OperationType.Query); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout( feedResponseFlux, endToEndPolicyConfig, options, isQueryCancelledOnTimeout, diagnosticsClientContext); } return feedResponseFlux; }, Queues.SMALL_BUFFER_SIZE, 1); } private static void applyExceptionToMergedDiagnosticsForQuery( CosmosQueryRequestOptions requestOptions, CosmosException exception, DiagnosticsClientContext diagnosticsClientContext) { CosmosDiagnostics mostRecentlyCreatedDiagnostics = diagnosticsClientContext.getMostRecentlyCreatedDiagnostics(); if (mostRecentlyCreatedDiagnostics != null) { BridgeInternal.setCosmosDiagnostics( exception, mostRecentlyCreatedDiagnostics); } else { List<CosmosDiagnostics> cancelledRequestDiagnostics = qryOptAccessor .getCancelledRequestDiagnosticsTracker(requestOptions); if (cancelledRequestDiagnostics != null && !cancelledRequestDiagnostics.isEmpty()) { CosmosDiagnostics aggregratedCosmosDiagnostics = cancelledRequestDiagnostics .stream() .reduce((first, toBeMerged) -> { ClientSideRequestStatistics clientSideRequestStatistics = ImplementationBridgeHelpers .CosmosDiagnosticsHelper .getCosmosDiagnosticsAccessor() .getClientSideRequestStatisticsRaw(first); ClientSideRequestStatistics toBeMergedClientSideRequestStatistics = ImplementationBridgeHelpers .CosmosDiagnosticsHelper .getCosmosDiagnosticsAccessor() .getClientSideRequestStatisticsRaw(first); if (clientSideRequestStatistics == null) { return toBeMerged; } else { clientSideRequestStatistics.mergeClientSideRequestStatistics(toBeMergedClientSideRequestStatistics); return first; } }) .get(); BridgeInternal.setCosmosDiagnostics(exception, aggregratedCosmosDiagnostics); } } } private static <T> Flux<FeedResponse<T>> getFeedResponseFluxWithTimeout( Flux<FeedResponse<T>> feedResponseFlux, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, CosmosQueryRequestOptions requestOptions, final AtomicBoolean isQueryCancelledOnTimeout, DiagnosticsClientContext diagnosticsClientContext) { Duration endToEndTimeout = endToEndPolicyConfig.getEndToEndOperationTimeout(); if (endToEndTimeout.isNegative()) { return feedResponseFlux .timeout(endToEndTimeout) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException cancellationException = getNegativeTimeoutException(null, endToEndTimeout); cancellationException.setStackTrace(throwable.getStackTrace()); isQueryCancelledOnTimeout.set(true); applyExceptionToMergedDiagnosticsForQuery( requestOptions, cancellationException, diagnosticsClientContext); return cancellationException; } return throwable; }); } return feedResponseFlux .timeout(endToEndTimeout) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); isQueryCancelledOnTimeout.set(true); applyExceptionToMergedDiagnosticsForQuery(requestOptions, exception, diagnosticsClientContext); return exception; } return throwable; }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, QueryFeedOperationState state) { return queryDatabases(new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(Paths.DATABASES_ROOT, querySpec, state, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, QueryFeedOperationState state) { return createQuery(databaseLink, new SqlQuerySpec(query), state, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if (options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null) { if (options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } if (options.getDedicatedGatewayRequestOptions().isIntegratedCacheBypassed()) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_BYPASS_CACHE, String.valueOf(options.getDedicatedGatewayRequestOptions().isIntegratedCacheBypassed())); } } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = PartitionKeyHelper.extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType, DiagnosticsClientContext clientContextOverride) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); String trackingId = null; if (options != null) { trackingId = options.getTrackingId(); } ByteBuffer content = InternalObjectNode.serializeJsonToByteBuffer(document, mapper, trackingId); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), operationType, ResourceType.Document, path, requestHeaders, options, content); if (operationType.isWriteOperation() && options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if( options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } if (options != null) { request.requestContext.setExcludeRegions(options.getExcludeRegions()); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } this.populateCapabilitiesHeader(request); if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private void populateCapabilitiesHeader(RxDocumentServiceRequest request) { if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES)) { request .getHeaders() .put(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); } } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Create, (opt, e2ecfg, clientCtxOverride) -> createDocumentCore( collectionLink, document, opt, disableAutomaticIdGeneration, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> createDocumentCore( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); if (nonNullRequestOptions.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal( collectionLink, document, nonNullRequestOptions, disableAutomaticIdGeneration, finalRetryPolicyInstance, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> createDocumentInternal( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy, DiagnosticsClientContext clientContextOverride) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create, clientContextOverride); return requestObs .flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } private static <T> Mono<T> getPointOperationResponseMonoWithE2ETimeout( RequestOptions requestOptions, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, Mono<T> rxDocumentServiceResponseMono, ScopedDiagnosticsFactory scopedDiagnosticsFactory) { requestOptions.setCosmosEndToEndLatencyPolicyConfig(endToEndPolicyConfig); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { Duration endToEndTimeout = endToEndPolicyConfig.getEndToEndOperationTimeout(); if (endToEndTimeout.isNegative()) { CosmosDiagnostics latestCosmosDiagnosticsSnapshot = scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(); if (latestCosmosDiagnosticsSnapshot == null) { scopedDiagnosticsFactory.createDiagnostics(); } return Mono.error(getNegativeTimeoutException(scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(), endToEndTimeout)); } return rxDocumentServiceResponseMono .timeout(endToEndTimeout) .onErrorMap(throwable -> getCancellationExceptionForPointOperations( scopedDiagnosticsFactory, throwable, requestOptions.getMarkE2ETimeoutInRequestContextCallbackHook())); } return rxDocumentServiceResponseMono; } private static Throwable getCancellationExceptionForPointOperations( ScopedDiagnosticsFactory scopedDiagnosticsFactory, Throwable throwable, AtomicReference<Runnable> markE2ETimeoutInRequestContextCallbackHook) { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); if (unwrappedException instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); Runnable actualCallback = markE2ETimeoutInRequestContextCallbackHook.get(); if (actualCallback != null) { logger.trace("Calling actual Mark E2E timeout callback"); actualCallback.run(); } CosmosDiagnostics lastDiagnosticsSnapshot = scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(); if (lastDiagnosticsSnapshot == null) { scopedDiagnosticsFactory.createDiagnostics(); } BridgeInternal.setCosmosDiagnostics(exception, scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics()); return exception; } return throwable; } private static CosmosException getNegativeTimeoutException(CosmosDiagnostics cosmosDiagnostics, Duration negativeTimeout) { checkNotNull(negativeTimeout, "Argument 'negativeTimeout' must not be null"); checkArgument( negativeTimeout.isNegative(), "This exception should only be used for negative timeouts"); String message = String.format("Negative timeout '%s' provided.", negativeTimeout); CosmosException exception = new OperationCancelledException(message, null); BridgeInternal.setSubStatusCode(exception, HttpConstants.SubStatusCodes.NEGATIVE_TIMEOUT_PROVIDED); if (cosmosDiagnostics != null) { BridgeInternal.setCosmosDiagnostics(exception, cosmosDiagnostics); } return exception; } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Upsert, (opt, e2ecfg, clientCtxOverride) -> upsertDocumentCore( collectionLink, document, opt, disableAutomaticIdGeneration, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> upsertDocumentCore( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); if (nonNullRequestOptions.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> upsertDocumentInternal( collectionLink, document, nonNullRequestOptions, disableAutomaticIdGeneration, finalRetryPolicyInstance, scopedDiagnosticsFactory), finalRetryPolicyInstance), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> upsertDocumentInternal( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest( retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert, clientContextOverride); return reqObs .flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Replace, (opt, e2ecfg, clientCtxOverride) -> replaceDocumentCore( documentLink, document, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> replaceDocumentCore( String documentLink, Object document, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); if (nonNullRequestOptions.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy( collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> replaceDocumentInternal( documentLink, document, nonNullRequestOptions, finalRequestRetryPolicy, endToEndPolicyConfig, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> replaceDocumentInternal( String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal( documentLink, typedDocument, options, retryPolicyInstance, clientContextOverride); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Replace, (opt, e2ecfg, clientCtxOverride) -> replaceDocumentCore( document, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> replaceDocumentCore( Document document, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(clientContextOverride); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy( collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs( () -> replaceDocumentInternal( document, options, finalRequestRetryPolicy, endToEndPolicyConfig, clientContextOverride), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal( Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal( document.getSelfLink(), document, options, retryPolicyInstance, clientContextOverride); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal( String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); if (options != null) { String trackingId = options.getTrackingId(); if (trackingId != null && !trackingId.isEmpty()) { document.set(Constants.Properties.TRACKING_ID, trackingId); } } ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs .flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } private CosmosEndToEndOperationLatencyPolicyConfig getEndToEndOperationLatencyPolicyConfig( RequestOptions options, ResourceType resourceType, OperationType operationType) { return this.getEffectiveEndToEndOperationLatencyPolicyConfig( options != null ? options.getCosmosEndToEndLatencyPolicyConfig() : null, resourceType, operationType); } private CosmosEndToEndOperationLatencyPolicyConfig getEffectiveEndToEndOperationLatencyPolicyConfig( CosmosEndToEndOperationLatencyPolicyConfig policyConfig, ResourceType resourceType, OperationType operationType) { if (policyConfig != null) { return policyConfig; } if (resourceType != ResourceType.Document) { return null; } if (!operationType.isPointOperation() && Configs.isDefaultE2ETimeoutDisabledForNonPointOperations()) { return null; } return this.cosmosEndToEndOperationLatencyPolicyConfig; } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Patch, (opt, e2ecfg, clientCtxOverride) -> patchDocumentCore( documentLink, cosmosPatchOperations, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> patchDocumentCore( String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> patchDocumentInternal( documentLink, cosmosPatchOperations, nonNullRequestOptions, documentClientRetryPolicy, scopedDiagnosticsFactory), documentClientRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> patchDocumentInternal( String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap( PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( clientContextOverride, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs .flatMap(req -> patch(request, retryPolicyInstance)) .map(resp -> toResourceResponse(resp, Document.class)); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Delete, (opt, e2ecfg, clientCtxOverride) -> deleteDocumentCore( documentLink, null, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Delete, (opt, e2ecfg, clientCtxOverride) -> deleteDocumentCore( documentLink, internalObjectNode, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> deleteDocumentCore( String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> deleteDocumentInternal( documentLink, internalObjectNode, nonNullRequestOptions, requestRetryPolicy, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> deleteDocumentInternal( String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, internalObjectNode, options, collectionObs); return requestObs .flatMap(req -> this.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { return readDocument(documentLink, options, this); } private Mono<ResourceResponse<Document>> readDocument( String documentLink, RequestOptions options, DiagnosticsClientContext innerDiagnosticsFactory) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Read, (opt, e2ecfg, clientCtxOverride) -> readDocumentCore(documentLink, opt, e2ecfg, clientCtxOverride), options, false, innerDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> readDocumentCore( String documentLink, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> readDocumentInternal( documentLink, nonNullRequestOptions, retryPolicyInstance, scopedDiagnosticsFactory), retryPolicyInstance), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> readDocumentInternal( String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Read, ResourceType.Document, path, requestHeaders, options); options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this.read(request, retryPolicyInstance) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, QueryFeedOperationState state, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", state, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, QueryFeedOperationState state, Class<T> klass) { final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(this, true); state.registerDiagnosticsFactory( () -> {}, (ctx) -> diagnosticsFactory.merge(ctx) ); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(diagnosticsFactory, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono .flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } itemIdentityList .forEach(itemIdentity -> { if (pkDefinition.getKind().equals(PartitionKind.MULTI_HASH) && ModelBridgeInternal.getPartitionKeyInternal(itemIdentity.getPartitionKey()) .getComponents().size() != pkDefinition.getPaths().size()) { throw new IllegalArgumentException(RMResources.PartitionKeyMismatch); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); Flux<FeedResponse<T>> pointReads = pointReadsForReadMany( diagnosticsFactory, partitionRangeItemKeyMap, resourceLink, state.getQueryOptions(), klass); Flux<FeedResponse<T>> queries = queryForReadMany( diagnosticsFactory, resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), state.getQueryOptions(), klass, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)); return Flux.merge(pointReads, queries) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); Collection<ClientSideRequestStatistics> aggregateRequestStatistics = new DistinctClientSideRequestStatisticsCollection(); double requestCharge = 0; for (FeedResponse<T> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults()); aggregateRequestStatistics.addAll(diagnosticsAccessor.getClientSideRequestStatistics(page.getCosmosDiagnostics())); } CosmosDiagnostics aggregatedDiagnostics = BridgeInternal.createCosmosDiagnostics(aggregatedQueryMetrics); diagnosticsAccessor.addClientSideDiagnosticsToFeed( aggregatedDiagnostics, aggregateRequestStatistics); state.mergeDiagnosticsContext(); CosmosDiagnosticsContext ctx = state.getDiagnosticsContextSnapshot(); if (ctx != null) { ctxAccessor.recordOperation( ctx, 200, 0, finalList.size(), requestCharge, aggregatedDiagnostics, null ); diagnosticsAccessor .setDiagnosticsContext( aggregatedDiagnostics, ctx); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponseWithQueryMetrics( finalList, headers, aggregatedQueryMetrics, null, false, false, aggregatedDiagnostics); return frp; }); }) .onErrorMap(throwable -> { if (throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException)throwable; CosmosDiagnostics diagnostics = cosmosException.getDiagnostics(); if (diagnostics != null) { state.mergeDiagnosticsContext(); CosmosDiagnosticsContext ctx = state.getDiagnosticsContextSnapshot(); if (ctx != null) { ctxAccessor.recordOperation( ctx, cosmosException.getStatusCode(), cosmosException.getSubStatusCode(), 0, cosmosException.getRequestCharge(), diagnostics, throwable ); diagnosticsAccessor .setDiagnosticsContext( diagnostics, state.getDiagnosticsContextSnapshot()); } } return cosmosException; } return throwable; }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); List<String> partitionKeySelectors = createPkSelectors(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; List<CosmosItemIdentity> cosmosItemIdentityList = entry.getValue(); if (cosmosItemIdentityList.size() > 1) { if (partitionKeySelectors.size() == 1 && partitionKeySelectors.get(0).equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(cosmosItemIdentityList); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelectors); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(List<CosmosItemIdentity> idPartitionKeyPairList) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec( List<CosmosItemIdentity> itemIdentities, List<String> partitionKeySelectors) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); int paramCount = 0; for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object[] pkValues = ModelBridgeInternal.getPartitionKeyInternal(pkValueAsPartitionKey).toObjectArray(); List<List<String>> partitionKeyParams = new ArrayList<>(); int pathCount = 0; for (Object pkComponentValue : pkValues) { String pkParamName = "@param" + paramCount; partitionKeyParams.add(Arrays.asList(partitionKeySelectors.get(pathCount), pkParamName)); parameters.add(new SqlParameter(pkParamName, pkComponentValue)); paramCount++; pathCount++; } String idValue = itemIdentity.getId(); String idParamName = "@param" + paramCount; paramCount++; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); for (List<String> pkParam: partitionKeyParams) { queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(pkParam.get(0)); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParam.get(1)); } queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private List<String> createPkSelectors(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.toList()); } private <T> Flux<FeedResponse<T>> queryForReadMany( ScopedDiagnosticsFactory diagnosticsFactory, String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { if (rangeQueryMap.isEmpty()) { return Flux.empty(); } UUID activityId = randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync( diagnosticsFactory, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum, isQueryCancelledOnTimeout); Flux<FeedResponse<T>> feedResponseFlux = executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions, ResourceType.Document, OperationType.Query); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout( feedResponseFlux, endToEndPolicyConfig, options, isQueryCancelledOnTimeout, diagnosticsFactory); } return feedResponseFlux; } private <T> Flux<FeedResponse<T>> pointReadsForReadMany( ScopedDiagnosticsFactory diagnosticsFactory, Map<PartitionKeyRange, List<CosmosItemIdentity>> singleItemPartitionRequestMap, String resourceLink, CosmosQueryRequestOptions queryRequestOptions, Class<T> klass) { ItemDeserializer effectiveItemDeserializer = getEffectiveItemDeserializer(queryRequestOptions, klass); return Flux.fromIterable(singleItemPartitionRequestMap.values()) .flatMap(cosmosItemIdentityList -> { if (cosmosItemIdentityList.size() == 1) { CosmosItemIdentity firstIdentity = cosmosItemIdentityList.get(0); RequestOptions requestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(queryRequestOptions); requestOptions.setPartitionKey(firstIdentity.getPartitionKey()); return this.readDocument((resourceLink + firstIdentity.getId()), requestOptions, diagnosticsFactory) .flatMap(resourceResponse -> Mono.just( new ImmutablePair<ResourceResponse<Document>, CosmosException>(resourceResponse, null) )) .onErrorResume(throwable -> { Throwable unwrappedThrowable = Exceptions.unwrap(throwable); if (unwrappedThrowable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) unwrappedThrowable; int statusCode = cosmosException.getStatusCode(); int subStatusCode = cosmosException.getSubStatusCode(); if (statusCode == HttpConstants.StatusCodes.NOTFOUND && subStatusCode == HttpConstants.SubStatusCodes.UNKNOWN) { return Mono.just(new ImmutablePair<ResourceResponse<Document>, CosmosException>(null, cosmosException)); } } return Mono.error(unwrappedThrowable); }); } return Mono.empty(); }) .flatMap(resourceResponseToExceptionPair -> { ResourceResponse<Document> resourceResponse = resourceResponseToExceptionPair.getLeft(); CosmosException cosmosException = resourceResponseToExceptionPair.getRight(); FeedResponse<T> feedResponse; if (cosmosException != null) { feedResponse = ModelBridgeInternal.createFeedResponse(new ArrayList<>(), cosmosException.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosException.getDiagnostics()))); } else { CosmosItemResponse<T> cosmosItemResponse = ModelBridgeInternal.createCosmosAsyncItemResponse(resourceResponse, klass, effectiveItemDeserializer); feedResponse = ModelBridgeInternal.createFeedResponse( Arrays.asList(cosmosItemResponse.getItem()), cosmosItemResponse.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosItemResponse.getDiagnostics()))); } return Mono.just(feedResponse); }); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, QueryFeedOperationState state, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), state, classOfT); } private <T> ItemDeserializer getEffectiveItemDeserializer( CosmosQueryRequestOptions queryRequestOptions, Class<T> klass) { Function<JsonNode, T> factoryMethod = queryRequestOptions == null ? null : qryOptAccessor.getImpl(queryRequestOptions).getItemFactoryMethod(klass); if (factoryMethod == null) { return this.itemDeserializer; } return new ItemDeserializer.JsonDeserializer(factoryMethod); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public <T> Mono<T> executeFeedOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, Supplier<DocumentClientRetryPolicy> retryPolicyFactory, RxDocumentServiceRequest req, BiFunction<Supplier<DocumentClientRetryPolicy>, RxDocumentServiceRequest, Mono<T>> feedOperation) { return RxDocumentClientImpl.this.executeFeedOperationWithAvailabilityStrategy( resourceType, operationType, retryPolicyFactory, req, feedOperation ); } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, state, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeedFromPagedFlux(DocumentCollection collection, ChangeFeedOperationState state, Class<T> classOfT) { return queryDocumentChangeFeed(collection, state.getChangeFeedOptions(), classOfT); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, QueryFeedOperationState state, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } final CosmosQueryRequestOptions effectiveOptions = qryOptAccessor.clone(state.getQueryOptions()); RequestOptions nonNullRequestOptions = qryOptAccessor.toRequestOptions(effectiveOptions); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = nonNullRequestOptions.getCosmosEndToEndLatencyPolicyConfig(); List<String> orderedApplicableRegionsForSpeculation = getApplicableRegionsForSpeculation( endToEndPolicyConfig, ResourceType.Document, OperationType.Query, false, nonNullRequestOptions); ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(this, false); if (orderedApplicableRegionsForSpeculation.size() < 2) { state.registerDiagnosticsFactory( () -> {}, (ctx) -> diagnosticsFactory.merge(ctx)); } else { state.registerDiagnosticsFactory( () -> diagnosticsFactory.reset(), (ctx) -> diagnosticsFactory.merge(ctx)); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create( diagnosticsFactory, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); List<String> partitionKeySelectors = createPkSelectors(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, partitionKeySelectors); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(state.getQueryOptions())); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); Flux<FeedResponse<T>> innerFlux = ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( diagnosticsFactory, resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId, isQueryCancelledOnTimeout); }); }, invalidPartitionExceptionRetryPolicy); if (orderedApplicableRegionsForSpeculation.size() < 2) { return innerFlux; } return innerFlux .flatMap(result -> { diagnosticsFactory.merge(nonNullRequestOptions); return Mono.just(result); }) .onErrorMap(throwable -> { diagnosticsFactory.merge(nonNullRequestOptions); return throwable; }) .doOnCancel(() -> diagnosticsFactory.merge(nonNullRequestOptions)); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, QueryFeedOperationState state) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (options != null) { request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, QueryFeedOperationState state) { return queryTriggers(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions( String collectionLink, String query, QueryFeedOperationState state) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions( String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, QueryFeedOperationState state) { return queryConflicts(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, QueryFeedOperationState state) { return queryUsers(databaseLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys( String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys( String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy(null)); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return nonDocumentReadFeed(state, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, QueryFeedOperationState state) { return queryPermissions(userLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(userLink, querySpec, state, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(QueryFeedOperationState state) { return nonDocumentReadFeed(state, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeed( QueryFeedOperationState state, ResourceType resourceType, Class<T> klass, String resourceLink) { return nonDocumentReadFeed(state.getQueryOptions(), resourceType, klass, resourceLink); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> nonDocumentReadFeedInternal(options, resourceType, klass, resourceLink, retryPolicy), retryPolicy); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeedInternal( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink, DocumentClientRetryPolicy retryPolicy) { final CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions(); Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(nonNullOptions); int maxPageSize = maxItemCount != null ? maxItemCount : -1; assert(resourceType != ResourceType.Document); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, nonNullOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> readFeed(request) .map(response -> toFeedResponsePage( response, qryOptAccessor.getImpl(nonNullOptions).getItemFactoryMethod(klass), klass)); return Paginator .getPaginatedQueryResultAsObservable( nonNullOptions, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, QueryFeedOperationState state) { return queryOffers(new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(null, querySpec, state, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } @Override public GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } @Override public AddressSelector getAddressSelector() { return new AddressSelector(this.addressResolver, this.configs.getProtocol()); } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.useGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); if (ConnectionMode.DIRECT == this.connectionPolicy.getConnectionMode()) { this.storeModel.enableThroughputControl(throughputControlStore); } else { this.gatewayProxy.enableThroughputControl(throughputControlStore); } } this.throughputControlStore.enableThroughputControlGroup(group, throughputQueryMono); } @Override public Flux<Void> submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig) { return this.storeModel.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig); } @Override public ConsistencyLevel getDefaultConsistencyLevelOfAccount() { return this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } /*** * Configure fault injector provider. * * @param injectorProvider the fault injector provider. */ @Override public void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) { checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null"); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.DIRECT) { this.storeModel.configureFaultInjectorProvider(injectorProvider, this.configs); this.addressResolver.configureFaultInjectorProvider(injectorProvider, this.configs); } this.gatewayProxy.configureFaultInjectorProvider(injectorProvider, this.configs); } @Override public void recordOpenConnectionsAndInitCachesCompleted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesCompleted(cosmosContainerIdentities); } @Override public void recordOpenConnectionsAndInitCachesStarted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesStarted(cosmosContainerIdentities); } @Override public String getMasterKeyOrResourceToken() { return this.masterKeyOrResourceToken; } private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, List<String> partitionKeySelectors) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object[] pkValues = ModelBridgeInternal.getPartitionKeyInternal(partitionKey).toObjectArray(); String pkParamNamePrefix = "@pkValue"; for (int i = 0; i < pkValues.length; i++) { StringBuilder subQueryStringBuilder = new StringBuilder(); String sqlParameterName = pkParamNamePrefix + i; if (i > 0) { subQueryStringBuilder.append(" AND "); } subQueryStringBuilder.append(" c"); subQueryStringBuilder.append(partitionKeySelectors.get(i)); subQueryStringBuilder.append((" = ")); subQueryStringBuilder.append(sqlParameterName); parameters.add(new SqlParameter(sqlParameterName, pkValues[i])); queryStringBuilder.append(subQueryStringBuilder); } return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink, boolean forceRefresh) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink, forceRefresh), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal( RxDocumentServiceRequest request, String collectionLink, boolean forceRefresh) { logger.debug("getFeedRange collectionLink=[{}] - forceRefresh={}", collectionLink, forceRefresh); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, forceRefresh, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } /** * Creates a type 4 (pseudo randomly generated) UUID. * <p> * The {@link UUID} is generated using a non-cryptographically strong pseudo random number generator. * * @return A randomly generated {@link UUID}. */ public static UUID randomUuid() { return randomUuid(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); } static UUID randomUuid(long msb, long lsb) { msb &= 0xffffffffffff0fffL; msb |= 0x0000000000004000L; lsb &= 0x3fffffffffffffffL; lsb |= 0x8000000000000000L; return new UUID(msb, lsb); } private Mono<ResourceResponse<Document>> wrapPointOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, DocumentPointOperation callback, RequestOptions initialRequestOptions, boolean idempotentWriteRetriesEnabled) { return wrapPointOperationWithAvailabilityStrategy( resourceType, operationType, callback, initialRequestOptions, idempotentWriteRetriesEnabled, this ); } private Mono<ResourceResponse<Document>> wrapPointOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, DocumentPointOperation callback, RequestOptions initialRequestOptions, boolean idempotentWriteRetriesEnabled, DiagnosticsClientContext innerDiagnosticsFactory) { checkNotNull(resourceType, "Argument 'resourceType' must not be null."); checkNotNull(operationType, "Argument 'operationType' must not be null."); checkNotNull(callback, "Argument 'callback' must not be null."); final RequestOptions nonNullRequestOptions = initialRequestOptions != null ? initialRequestOptions : new RequestOptions(); checkArgument( resourceType == ResourceType.Document, "This method can only be used for document point operations."); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(nonNullRequestOptions, resourceType, operationType); List<String> orderedApplicableRegionsForSpeculation = getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, idempotentWriteRetriesEnabled, nonNullRequestOptions); if (orderedApplicableRegionsForSpeculation.size() < 2) { return callback.apply(nonNullRequestOptions, endToEndPolicyConfig, innerDiagnosticsFactory); } ThresholdBasedAvailabilityStrategy availabilityStrategy = (ThresholdBasedAvailabilityStrategy)endToEndPolicyConfig.getAvailabilityStrategy(); List<Mono<NonTransientPointOperationResult>> monoList = new ArrayList<>(); final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(innerDiagnosticsFactory, false); orderedApplicableRegionsForSpeculation .forEach(region -> { RequestOptions clonedOptions = new RequestOptions(nonNullRequestOptions); if (monoList.isEmpty()) { Mono<NonTransientPointOperationResult> initialMonoAcrossAllRegions = callback.apply(clonedOptions, endToEndPolicyConfig, diagnosticsFactory) .map(NonTransientPointOperationResult::new) .onErrorResume( RxDocumentClientImpl::isCosmosException, t -> Mono.just( new NonTransientPointOperationResult( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); if (logger.isDebugEnabled()) { monoList.add(initialMonoAcrossAllRegions.doOnSubscribe(c -> logger.debug( "STARTING to process {} operation in region '{}'", operationType, region))); } else { monoList.add(initialMonoAcrossAllRegions); } } else { clonedOptions.setExcludeRegions( getEffectiveExcludedRegionsForHedging( nonNullRequestOptions.getExcludeRegions(), orderedApplicableRegionsForSpeculation, region) ); Mono<NonTransientPointOperationResult> regionalCrossRegionRetryMono = callback.apply(clonedOptions, endToEndPolicyConfig, diagnosticsFactory) .map(NonTransientPointOperationResult::new) .onErrorResume( RxDocumentClientImpl::isNonTransientCosmosException, t -> Mono.just( new NonTransientPointOperationResult( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); Duration delayForCrossRegionalRetry = (availabilityStrategy) .getThreshold() .plus((availabilityStrategy) .getThresholdStep() .multipliedBy(monoList.size() - 1)); if (logger.isDebugEnabled()) { monoList.add( regionalCrossRegionRetryMono .doOnSubscribe(c -> logger.debug("STARTING to process {} operation in region '{}'", operationType, region)) .delaySubscription(delayForCrossRegionalRetry)); } else { monoList.add( regionalCrossRegionRetryMono .delaySubscription(delayForCrossRegionalRetry)); } } }); return Mono .firstWithValue(monoList) .flatMap(nonTransientResult -> { diagnosticsFactory.merge(nonNullRequestOptions); if (nonTransientResult.isError()) { return Mono.error(nonTransientResult.exception); } return Mono.just(nonTransientResult.response); }) .onErrorMap(throwable -> { Throwable exception = Exceptions.unwrap(throwable); if (exception instanceof NoSuchElementException) { List<Throwable> innerThrowables = Exceptions .unwrapMultiple(exception.getCause()); int index = 0; for (Throwable innerThrowable : innerThrowables) { Throwable innerException = Exceptions.unwrap(innerThrowable); if (innerException instanceof CosmosException) { CosmosException cosmosException = Utils.as(innerException, CosmosException.class); diagnosticsFactory.merge(nonNullRequestOptions); return cosmosException; } else if (innerException instanceof NoSuchElementException) { logger.trace( "Operation in {} completed with empty result because it was cancelled.", orderedApplicableRegionsForSpeculation.get(index)); } else if (logger.isWarnEnabled()) { String message = "Unexpected Non-CosmosException when processing operation in '" + orderedApplicableRegionsForSpeculation.get(index) + "'."; logger.warn( message, innerException ); } index++; } } diagnosticsFactory.merge(nonNullRequestOptions); return exception; }) .doOnCancel(() -> diagnosticsFactory.merge(nonNullRequestOptions)); } private static boolean isCosmosException(Throwable t) { final Throwable unwrappedException = Exceptions.unwrap(t); return unwrappedException instanceof CosmosException; } private static boolean isNonTransientCosmosException(Throwable t) { final Throwable unwrappedException = Exceptions.unwrap(t); if (!(unwrappedException instanceof CosmosException)) { return false; } CosmosException cosmosException = Utils.as(unwrappedException, CosmosException.class); return isNonTransientResultForHedging( cosmosException.getStatusCode(), cosmosException.getSubStatusCode()); } private List<String> getEffectiveExcludedRegionsForHedging( List<String> initialExcludedRegions, List<String> applicableRegions, String currentRegion) { List<String> effectiveExcludedRegions = new ArrayList<>(); if (initialExcludedRegions != null) { effectiveExcludedRegions.addAll(initialExcludedRegions); } for (String applicableRegion: applicableRegions) { if (!applicableRegion.equals(currentRegion)) { effectiveExcludedRegions.add(applicableRegion); } } return effectiveExcludedRegions; } private static boolean isNonTransientResultForHedging(int statusCode, int subStatusCode) { if (statusCode < HttpConstants.StatusCodes.BADREQUEST) { return true; } if (statusCode == HttpConstants.StatusCodes.REQUEST_TIMEOUT && subStatusCode == HttpConstants.SubStatusCodes.CLIENT_OPERATION_TIMEOUT) { return true; } if (statusCode == HttpConstants.StatusCodes.BADREQUEST || statusCode == HttpConstants.StatusCodes.CONFLICT || statusCode == HttpConstants.StatusCodes.METHOD_NOT_ALLOWED || statusCode == HttpConstants.StatusCodes.PRECONDITION_FAILED || statusCode == HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE || statusCode == HttpConstants.StatusCodes.UNAUTHORIZED) { return true; } if (statusCode == HttpConstants.StatusCodes.NOTFOUND && subStatusCode == HttpConstants.SubStatusCodes.UNKNOWN) { return true; } return false; } private DiagnosticsClientContext getEffectiveClientContext(DiagnosticsClientContext clientContextOverride) { if (clientContextOverride != null) { return clientContextOverride; } return this; } /** * Returns the applicable endpoints ordered by preference list if any * @param operationType - the operationT * @return the applicable endpoints ordered by preference list if any */ private List<URI> getApplicableEndPoints(OperationType operationType, List<String> excludedRegions) { if (operationType.isReadOnlyOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableReadEndpoints(excludedRegions)); } else if (operationType.isWriteOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableWriteEndpoints(excludedRegions)); } return EMPTY_ENDPOINT_LIST; } private static List<URI> withoutNulls(List<URI> orderedEffectiveEndpointsList) { if (orderedEffectiveEndpointsList == null) { return EMPTY_ENDPOINT_LIST; } int i = 0; while (i < orderedEffectiveEndpointsList.size()) { if (orderedEffectiveEndpointsList.get(i) == null) { orderedEffectiveEndpointsList.remove(i); } else { i++; } } return orderedEffectiveEndpointsList; } private List<String> getApplicableRegionsForSpeculation( CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, ResourceType resourceType, OperationType operationType, boolean isIdempotentWriteRetriesEnabled, RequestOptions options) { return getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, isIdempotentWriteRetriesEnabled, options.getExcludeRegions()); } private List<String> getApplicableRegionsForSpeculation( CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, ResourceType resourceType, OperationType operationType, boolean isIdempotentWriteRetriesEnabled, List<String> excludedRegions) { if (endToEndPolicyConfig == null || !endToEndPolicyConfig.isEnabled()) { return EMPTY_REGION_LIST; } if (resourceType != ResourceType.Document) { return EMPTY_REGION_LIST; } if (operationType.isWriteOperation() && !isIdempotentWriteRetriesEnabled) { return EMPTY_REGION_LIST; } if (operationType.isWriteOperation() && !this.globalEndpointManager.canUseMultipleWriteLocations()) { return EMPTY_REGION_LIST; } if (!(endToEndPolicyConfig.getAvailabilityStrategy() instanceof ThresholdBasedAvailabilityStrategy)) { return EMPTY_REGION_LIST; } List<URI> endpoints = getApplicableEndPoints(operationType, excludedRegions); HashSet<String> normalizedExcludedRegions = new HashSet<>(); if (excludedRegions != null) { excludedRegions.forEach(r -> normalizedExcludedRegions.add(r.toLowerCase(Locale.ROOT))); } List<String> orderedRegionsForSpeculation = new ArrayList<>(); endpoints.forEach(uri -> { String regionName = this.globalEndpointManager.getRegionName(uri, operationType); if (!normalizedExcludedRegions.contains(regionName.toLowerCase(Locale.ROOT))) { orderedRegionsForSpeculation.add(regionName); } }); return orderedRegionsForSpeculation; } private <T> Mono<T> executeFeedOperationWithAvailabilityStrategy( final ResourceType resourceType, final OperationType operationType, final Supplier<DocumentClientRetryPolicy> retryPolicyFactory, final RxDocumentServiceRequest req, final BiFunction<Supplier<DocumentClientRetryPolicy>, RxDocumentServiceRequest, Mono<T>> feedOperation ) { checkNotNull(retryPolicyFactory, "Argument 'retryPolicyFactory' must not be null."); checkNotNull(req, "Argument 'req' must not be null."); assert(resourceType == ResourceType.Document); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = this.getEffectiveEndToEndOperationLatencyPolicyConfig( req.requestContext.getEndToEndOperationLatencyPolicyConfig(), resourceType, operationType); List<String> initialExcludedRegions = req.requestContext.getExcludeRegions(); List<String> orderedApplicableRegionsForSpeculation = this.getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, false, initialExcludedRegions ); if (orderedApplicableRegionsForSpeculation.size() < 2) { return feedOperation.apply(retryPolicyFactory, req); } ThresholdBasedAvailabilityStrategy availabilityStrategy = (ThresholdBasedAvailabilityStrategy)endToEndPolicyConfig.getAvailabilityStrategy(); List<Mono<NonTransientFeedOperationResult<T>>> monoList = new ArrayList<>(); orderedApplicableRegionsForSpeculation .forEach(region -> { RxDocumentServiceRequest clonedRequest = req.clone(); if (monoList.isEmpty()) { Mono<NonTransientFeedOperationResult<T>> initialMonoAcrossAllRegions = feedOperation.apply(retryPolicyFactory, clonedRequest) .map(NonTransientFeedOperationResult::new) .onErrorResume( RxDocumentClientImpl::isCosmosException, t -> Mono.just( new NonTransientFeedOperationResult<>( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); if (logger.isDebugEnabled()) { monoList.add(initialMonoAcrossAllRegions.doOnSubscribe(c -> logger.debug( "STARTING to process {} operation in region '{}'", operationType, region))); } else { monoList.add(initialMonoAcrossAllRegions); } } else { clonedRequest.requestContext.setExcludeRegions( getEffectiveExcludedRegionsForHedging( initialExcludedRegions, orderedApplicableRegionsForSpeculation, region) ); Mono<NonTransientFeedOperationResult<T>> regionalCrossRegionRetryMono = feedOperation.apply(retryPolicyFactory, clonedRequest) .map(NonTransientFeedOperationResult::new) .onErrorResume( RxDocumentClientImpl::isNonTransientCosmosException, t -> Mono.just( new NonTransientFeedOperationResult<>( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); Duration delayForCrossRegionalRetry = (availabilityStrategy) .getThreshold() .plus((availabilityStrategy) .getThresholdStep() .multipliedBy(monoList.size() - 1)); if (logger.isDebugEnabled()) { monoList.add( regionalCrossRegionRetryMono .doOnSubscribe(c -> logger.debug("STARTING to process {} operation in region '{}'", operationType, region)) .delaySubscription(delayForCrossRegionalRetry)); } else { monoList.add( regionalCrossRegionRetryMono .delaySubscription(delayForCrossRegionalRetry)); } } }); return Mono .firstWithValue(monoList) .flatMap(nonTransientResult -> { if (nonTransientResult.isError()) { return Mono.error(nonTransientResult.exception); } return Mono.just(nonTransientResult.response); }) .onErrorMap(throwable -> { Throwable exception = Exceptions.unwrap(throwable); if (exception instanceof NoSuchElementException) { List<Throwable> innerThrowables = Exceptions .unwrapMultiple(exception.getCause()); int index = 0; for (Throwable innerThrowable : innerThrowables) { Throwable innerException = Exceptions.unwrap(innerThrowable); if (innerException instanceof CosmosException) { return Utils.as(innerException, CosmosException.class); } else if (innerException instanceof NoSuchElementException) { logger.trace( "Operation in {} completed with empty result because it was cancelled.", orderedApplicableRegionsForSpeculation.get(index)); } else if (logger.isWarnEnabled()) { String message = "Unexpected Non-CosmosException when processing operation in '" + orderedApplicableRegionsForSpeculation.get(index) + "'."; logger.warn( message, innerException ); } index++; } } return exception; }); } @FunctionalInterface private interface DocumentPointOperation { Mono<ResourceResponse<Document>> apply(RequestOptions requestOptions, CosmosEndToEndOperationLatencyPolicyConfig endToEndOperationLatencyPolicyConfig, DiagnosticsClientContext clientContextOverride); } private static class NonTransientPointOperationResult { private final ResourceResponse<Document> response; private final CosmosException exception; public NonTransientPointOperationResult(CosmosException exception) { checkNotNull(exception, "Argument 'exception' must not be null."); this.exception = exception; this.response = null; } public NonTransientPointOperationResult(ResourceResponse<Document> response) { checkNotNull(response, "Argument 'response' must not be null."); this.exception = null; this.response = response; } public boolean isError() { return this.exception != null; } public CosmosException getException() { return this.exception; } public ResourceResponse<Document> getResponse() { return this.response; } } private static class NonTransientFeedOperationResult<T> { private final T response; private final CosmosException exception; public NonTransientFeedOperationResult(CosmosException exception) { checkNotNull(exception, "Argument 'exception' must not be null."); this.exception = exception; this.response = null; } public NonTransientFeedOperationResult(T response) { checkNotNull(response, "Argument 'response' must not be null."); this.exception = null; this.response = response; } public boolean isError() { return this.exception != null; } public CosmosException getException() { return this.exception; } public T getResponse() { return this.response; } } private static class ScopedDiagnosticsFactory implements DiagnosticsClientContext { private final AtomicBoolean isMerged = new AtomicBoolean(false); private final DiagnosticsClientContext inner; private final ConcurrentLinkedQueue<CosmosDiagnostics> createdDiagnostics; private final boolean shouldCaptureAllFeedDiagnostics; private final AtomicReference<CosmosDiagnostics> mostRecentlyCreatedDiagnostics = new AtomicReference<>(null); public ScopedDiagnosticsFactory(DiagnosticsClientContext inner, boolean shouldCaptureAllFeedDiagnostics) { checkNotNull(inner, "Argument 'inner' must not be null."); this.inner = inner; this.createdDiagnostics = new ConcurrentLinkedQueue<>(); this.shouldCaptureAllFeedDiagnostics = shouldCaptureAllFeedDiagnostics; } @Override public DiagnosticsClientConfig getConfig() { return inner.getConfig(); } @Override public CosmosDiagnostics createDiagnostics() { CosmosDiagnostics diagnostics = inner.createDiagnostics(); createdDiagnostics.add(diagnostics); mostRecentlyCreatedDiagnostics.set(diagnostics); return diagnostics; } @Override public String getUserAgent() { return inner.getUserAgent(); } @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return this.mostRecentlyCreatedDiagnostics.get(); } public void merge(RequestOptions requestOptions) { CosmosDiagnosticsContext knownCtx = null; if (requestOptions != null) { CosmosDiagnosticsContext ctxSnapshot = requestOptions.getDiagnosticsContextSnapshot(); if (ctxSnapshot != null) { knownCtx = requestOptions.getDiagnosticsContextSnapshot(); } } merge(knownCtx); } public void merge(CosmosDiagnosticsContext knownCtx) { if (!isMerged.compareAndSet(false, true)) { return; } CosmosDiagnosticsContext ctx = null; if (knownCtx != null) { ctx = knownCtx; } else { for (CosmosDiagnostics diagnostics : this.createdDiagnostics) { if (diagnostics.getDiagnosticsContext() != null) { ctx = diagnostics.getDiagnosticsContext(); break; } } } if (ctx == null) { return; } for (CosmosDiagnostics diagnostics : this.createdDiagnostics) { if (diagnostics.getDiagnosticsContext() == null && diagnosticsAccessor.isNotEmpty(diagnostics)) { if (this.shouldCaptureAllFeedDiagnostics && diagnosticsAccessor.getFeedResponseDiagnostics(diagnostics) != null) { AtomicBoolean isCaptured = diagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(diagnostics); if (isCaptured != null) { isCaptured.set(true); } } ctxAccessor.addDiagnostics(ctx, diagnostics); } } } public void reset() { this.createdDiagnostics.clear(); this.isMerged.set(false); } } }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private final static List<String> EMPTY_REGION_LIST = Collections.emptyList(); private final static List<URI> EMPTY_ENDPOINT_LIST = Collections.emptyList(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); private final static ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.CosmosClientTelemetryConfigAccessor telemetryCfgAccessor = ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.getCosmosClientTelemetryConfigAccessor(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsContextHelper.CosmosDiagnosticsContextAccessor ctxAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsContextHelper.getCosmosDiagnosticsContextAccessor(); private final static ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor qryOptAccessor = ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor(); private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final Map<String, Integer> clientMap = new ConcurrentHashMap<>(); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final static Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxGatewayStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private final Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private final ApiType apiType; private final CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig; private final AtomicReference<CosmosDiagnostics> mostRecentlyCreatedDiagnostics = new AtomicReference<>(null); private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; private final CosmosClientTelemetryConfig clientTelemetryConfig; private final String clientCorrelationId; private final SessionRetryOptions sessionRetryOptions; private final boolean sessionCapturingOverrideEnabled; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { this( serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig, sessionRetryOptions, containerProactiveInitConfig); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length == 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig, SessionRetryOptions sessionRetryOptions, CosmosContainerProactiveInitConfig containerProactiveInitConfig) { assert(clientTelemetryConfig != null); Boolean clientTelemetryEnabled = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .isSendClientTelemetryToServiceEnabled(clientTelemetryConfig); assert(clientTelemetryEnabled != null); activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.clientCorrelationId = Strings.isNullOrWhiteSpace(clientCorrelationId) ? String.format("%05d",this.clientId): clientCorrelationId; clientMap.put(serviceEndpoint.toString(), clientMap.getOrDefault(serviceEndpoint.toString(), 0) + 1); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withClientMap(clientMap); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); this.cosmosEndToEndOperationLatencyPolicyConfig = cosmosEndToEndOperationLatencyPolicyConfig; this.diagnosticsClientConfig.withEndToEndOperationLatencyPolicy(cosmosEndToEndOperationLatencyPolicyConfig); this.sessionRetryOptions = sessionRetryOptions; logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withConnectionPolicy(this.connectionPolicy); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); this.diagnosticsClientConfig.withProactiveContainerInitConfig(containerProactiveInitConfig); this.diagnosticsClientConfig.withSessionRetryOptions(sessionRetryOptions); this.sessionCapturingOverrideEnabled = sessionCapturingOverrideEnabled; boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; this.clientTelemetryConfig = clientTelemetryConfig; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { CosmosDiagnostics diagnostics = diagnosticsAccessor.create(this, telemetryCfgAccessor.getSamplingRate(this.clientTelemetryConfig)); this.mostRecentlyCreatedDiagnostics.set(diagnostics); return diagnostics; } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { Throwable databaseRefreshErrorSnapshot = this.globalEndpointManager.getLatestDatabaseRefreshError(); if (databaseRefreshErrorSnapshot != null) { logger.error("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: databaseRefreshErrorSnapshot ); throw new RuntimeException("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: databaseRefreshErrorSnapshot); } else { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed. Check if the endpoint is reachable and if your auth token " + "is valid. More info: https: } } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { (this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); (this.gatewayProxy).setCollectionCache(this.collectionCache); (this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); (this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations, this.sessionRetryOptions); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public String getClientCorrelationId() { return this.clientCorrelationId; } @Override public String getMachineId() { if (this.diagnosticsClientConfig == null) { return null; } return ClientTelemetry.getMachineId(diagnosticsClientConfig); } @Override public String getUserAgent() { return this.userAgentContainer.getUserAgent(); } @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return mostRecentlyCreatedDiagnostics.get(); } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(QueryFeedOperationState state) { return nonDocumentReadFeed(state, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return qryOptAccessor.getImpl(options).getOperationContextAndListenerTuple(); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, QueryFeedOperationState state, Class<T> klass, ResourceType resourceTypeEnum) { return createQuery(parentResourceLink, sqlQuery, state, klass, resourceTypeEnum, this); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, QueryFeedOperationState state, Class<T> klass, ResourceType resourceTypeEnum, DiagnosticsClientContext innerDiagnosticsFactory) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); CosmosQueryRequestOptions nonNullQueryOptions = state.getQueryOptions(); UUID correlationActivityIdOfRequestOptions = qryOptAccessor .getImpl(nonNullQueryOptions) .getCorrelationActivityId(); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(nonNullQueryOptions)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(nonNullQueryOptions)); final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(innerDiagnosticsFactory, false); state.registerDiagnosticsFactory( diagnosticsFactory::reset, diagnosticsFactory::merge); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( diagnosticsFactory, resourceLink, sqlQuery, state.getQueryOptions(), klass, resourceTypeEnum, queryClient, correlationActivityId, isQueryCancelledOnTimeout), invalidPartitionExceptionRetryPolicy ).flatMap(result -> { diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot()); return Mono.just(result); }) .onErrorMap(throwable -> { diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot()); return throwable; }) .doOnCancel(() -> diagnosticsFactory.merge(state.getDiagnosticsContextSnapshot())); } private <T> Flux<FeedResponse<T>> createQueryInternal( DiagnosticsClientContext diagnosticsClientContext, String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId, final AtomicBoolean isQueryCancelledOnTimeout) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(diagnosticsClientContext, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache, isQueryCancelledOnTimeout); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; Flux<FeedResponse<T>> feedResponseFlux = iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions, resourceTypeEnum, OperationType.Query); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout( feedResponseFlux, endToEndPolicyConfig, options, isQueryCancelledOnTimeout, diagnosticsClientContext); } return feedResponseFlux; }, Queues.SMALL_BUFFER_SIZE, 1); } private static void applyExceptionToMergedDiagnosticsForQuery( CosmosQueryRequestOptions requestOptions, CosmosException exception, DiagnosticsClientContext diagnosticsClientContext) { CosmosDiagnostics mostRecentlyCreatedDiagnostics = diagnosticsClientContext.getMostRecentlyCreatedDiagnostics(); if (mostRecentlyCreatedDiagnostics != null) { BridgeInternal.setCosmosDiagnostics( exception, mostRecentlyCreatedDiagnostics); } else { List<CosmosDiagnostics> cancelledRequestDiagnostics = qryOptAccessor .getCancelledRequestDiagnosticsTracker(requestOptions); if (cancelledRequestDiagnostics != null && !cancelledRequestDiagnostics.isEmpty()) { CosmosDiagnostics aggregratedCosmosDiagnostics = cancelledRequestDiagnostics .stream() .reduce((first, toBeMerged) -> { ClientSideRequestStatistics clientSideRequestStatistics = ImplementationBridgeHelpers .CosmosDiagnosticsHelper .getCosmosDiagnosticsAccessor() .getClientSideRequestStatisticsRaw(first); ClientSideRequestStatistics toBeMergedClientSideRequestStatistics = ImplementationBridgeHelpers .CosmosDiagnosticsHelper .getCosmosDiagnosticsAccessor() .getClientSideRequestStatisticsRaw(first); if (clientSideRequestStatistics == null) { return toBeMerged; } else { clientSideRequestStatistics.mergeClientSideRequestStatistics(toBeMergedClientSideRequestStatistics); return first; } }) .get(); BridgeInternal.setCosmosDiagnostics(exception, aggregratedCosmosDiagnostics); } } } private static <T> Flux<FeedResponse<T>> getFeedResponseFluxWithTimeout( Flux<FeedResponse<T>> feedResponseFlux, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, CosmosQueryRequestOptions requestOptions, final AtomicBoolean isQueryCancelledOnTimeout, DiagnosticsClientContext diagnosticsClientContext) { Duration endToEndTimeout = endToEndPolicyConfig.getEndToEndOperationTimeout(); if (endToEndTimeout.isNegative()) { return feedResponseFlux .timeout(endToEndTimeout) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException cancellationException = getNegativeTimeoutException(null, endToEndTimeout); cancellationException.setStackTrace(throwable.getStackTrace()); isQueryCancelledOnTimeout.set(true); applyExceptionToMergedDiagnosticsForQuery( requestOptions, cancellationException, diagnosticsClientContext); return cancellationException; } return throwable; }); } return feedResponseFlux .timeout(endToEndTimeout) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); isQueryCancelledOnTimeout.set(true); applyExceptionToMergedDiagnosticsForQuery(requestOptions, exception, diagnosticsClientContext); return exception; } return throwable; }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, QueryFeedOperationState state) { return queryDatabases(new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(Paths.DATABASES_ROOT, querySpec, state, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, QueryFeedOperationState state) { return createQuery(databaseLink, new SqlQuerySpec(query), state, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if (options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null) { if (options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } if (options.getDedicatedGatewayRequestOptions().isIntegratedCacheBypassed()) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_BYPASS_CACHE, String.valueOf(options.getDedicatedGatewayRequestOptions().isIntegratedCacheBypassed())); } } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = PartitionKeyHelper.extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType, DiagnosticsClientContext clientContextOverride) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); String trackingId = null; if (options != null) { trackingId = options.getTrackingId(); } ByteBuffer content = InternalObjectNode.serializeJsonToByteBuffer(document, mapper, trackingId); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), operationType, ResourceType.Document, path, requestHeaders, options, content); if (operationType.isWriteOperation() && options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if( options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } if (options != null) { request.requestContext.setExcludeRegions(options.getExcludeRegions()); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } this.populateCapabilitiesHeader(request); if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private void populateCapabilitiesHeader(RxDocumentServiceRequest request) { if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES)) { request .getHeaders() .put(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); } } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Create, (opt, e2ecfg, clientCtxOverride) -> createDocumentCore( collectionLink, document, opt, disableAutomaticIdGeneration, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> createDocumentCore( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); if (nonNullRequestOptions.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal( collectionLink, document, nonNullRequestOptions, disableAutomaticIdGeneration, finalRetryPolicyInstance, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> createDocumentInternal( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy, DiagnosticsClientContext clientContextOverride) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create, clientContextOverride); return requestObs .flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } private static <T> Mono<T> getPointOperationResponseMonoWithE2ETimeout( RequestOptions requestOptions, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, Mono<T> rxDocumentServiceResponseMono, ScopedDiagnosticsFactory scopedDiagnosticsFactory) { requestOptions.setCosmosEndToEndLatencyPolicyConfig(endToEndPolicyConfig); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { Duration endToEndTimeout = endToEndPolicyConfig.getEndToEndOperationTimeout(); if (endToEndTimeout.isNegative()) { CosmosDiagnostics latestCosmosDiagnosticsSnapshot = scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(); if (latestCosmosDiagnosticsSnapshot == null) { scopedDiagnosticsFactory.createDiagnostics(); } return Mono.error(getNegativeTimeoutException(scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(), endToEndTimeout)); } return rxDocumentServiceResponseMono .timeout(endToEndTimeout) .onErrorMap(throwable -> getCancellationExceptionForPointOperations( scopedDiagnosticsFactory, throwable, requestOptions.getMarkE2ETimeoutInRequestContextCallbackHook())); } return rxDocumentServiceResponseMono; } private static Throwable getCancellationExceptionForPointOperations( ScopedDiagnosticsFactory scopedDiagnosticsFactory, Throwable throwable, AtomicReference<Runnable> markE2ETimeoutInRequestContextCallbackHook) { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); if (unwrappedException instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); Runnable actualCallback = markE2ETimeoutInRequestContextCallbackHook.get(); if (actualCallback != null) { logger.trace("Calling actual Mark E2E timeout callback"); actualCallback.run(); } CosmosDiagnostics lastDiagnosticsSnapshot = scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics(); if (lastDiagnosticsSnapshot == null) { scopedDiagnosticsFactory.createDiagnostics(); } BridgeInternal.setCosmosDiagnostics(exception, scopedDiagnosticsFactory.getMostRecentlyCreatedDiagnostics()); return exception; } return throwable; } private static CosmosException getNegativeTimeoutException(CosmosDiagnostics cosmosDiagnostics, Duration negativeTimeout) { checkNotNull(negativeTimeout, "Argument 'negativeTimeout' must not be null"); checkArgument( negativeTimeout.isNegative(), "This exception should only be used for negative timeouts"); String message = String.format("Negative timeout '%s' provided.", negativeTimeout); CosmosException exception = new OperationCancelledException(message, null); BridgeInternal.setSubStatusCode(exception, HttpConstants.SubStatusCodes.NEGATIVE_TIMEOUT_PROVIDED); if (cosmosDiagnostics != null) { BridgeInternal.setCosmosDiagnostics(exception, cosmosDiagnostics); } return exception; } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Upsert, (opt, e2ecfg, clientCtxOverride) -> upsertDocumentCore( collectionLink, document, opt, disableAutomaticIdGeneration, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> upsertDocumentCore( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); if (nonNullRequestOptions.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> upsertDocumentInternal( collectionLink, document, nonNullRequestOptions, disableAutomaticIdGeneration, finalRetryPolicyInstance, scopedDiagnosticsFactory), finalRetryPolicyInstance), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> upsertDocumentInternal( String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest( retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert, clientContextOverride); return reqObs .flatMap(request -> upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Replace, (opt, e2ecfg, clientCtxOverride) -> replaceDocumentCore( documentLink, document, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> replaceDocumentCore( String documentLink, Object document, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); if (nonNullRequestOptions.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy( collectionCache, requestRetryPolicy, collectionLink, nonNullRequestOptions); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> replaceDocumentInternal( documentLink, document, nonNullRequestOptions, finalRequestRetryPolicy, endToEndPolicyConfig, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> replaceDocumentInternal( String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal( documentLink, typedDocument, options, retryPolicyInstance, clientContextOverride); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Replace, (opt, e2ecfg, clientCtxOverride) -> replaceDocumentCore( document, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> replaceDocumentCore( Document document, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(clientContextOverride); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy( collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs( () -> replaceDocumentInternal( document, options, finalRequestRetryPolicy, endToEndPolicyConfig, clientContextOverride), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal( Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal( document.getSelfLink(), document, options, retryPolicyInstance, clientContextOverride); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal( String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); if (options != null) { String trackingId = options.getTrackingId(); if (trackingId != null && !trackingId.isEmpty()) { document.set(Constants.Properties.TRACKING_ID, trackingId); } } ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs .flatMap(req -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } private CosmosEndToEndOperationLatencyPolicyConfig getEndToEndOperationLatencyPolicyConfig( RequestOptions options, ResourceType resourceType, OperationType operationType) { return this.getEffectiveEndToEndOperationLatencyPolicyConfig( options != null ? options.getCosmosEndToEndLatencyPolicyConfig() : null, resourceType, operationType); } private CosmosEndToEndOperationLatencyPolicyConfig getEffectiveEndToEndOperationLatencyPolicyConfig( CosmosEndToEndOperationLatencyPolicyConfig policyConfig, ResourceType resourceType, OperationType operationType) { if (policyConfig != null) { return policyConfig; } if (resourceType != ResourceType.Document) { return null; } if (!operationType.isPointOperation() && Configs.isDefaultE2ETimeoutDisabledForNonPointOperations()) { return null; } return this.cosmosEndToEndOperationLatencyPolicyConfig; } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Patch, (opt, e2ecfg, clientCtxOverride) -> patchDocumentCore( documentLink, cosmosPatchOperations, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> patchDocumentCore( String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> patchDocumentInternal( documentLink, cosmosPatchOperations, nonNullRequestOptions, documentClientRetryPolicy, scopedDiagnosticsFactory), documentClientRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> patchDocumentInternal( String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap( PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( clientContextOverride, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs .flatMap(req -> patch(request, retryPolicyInstance)) .map(resp -> toResourceResponse(resp, Document.class)); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Delete, (opt, e2ecfg, clientCtxOverride) -> deleteDocumentCore( documentLink, null, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Delete, (opt, e2ecfg, clientCtxOverride) -> deleteDocumentCore( documentLink, internalObjectNode, opt, e2ecfg, clientCtxOverride), options, options != null && options.getNonIdempotentWriteRetriesEnabled() ); } private Mono<ResourceResponse<Document>> deleteDocumentCore( String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> deleteDocumentInternal( documentLink, internalObjectNode, nonNullRequestOptions, requestRetryPolicy, scopedDiagnosticsFactory), requestRetryPolicy), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> deleteDocumentInternal( String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (options != null) { options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, internalObjectNode, options, collectionObs); return requestObs .flatMap(req -> this.delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options))) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { return readDocument(documentLink, options, this); } private Mono<ResourceResponse<Document>> readDocument( String documentLink, RequestOptions options, DiagnosticsClientContext innerDiagnosticsFactory) { return wrapPointOperationWithAvailabilityStrategy( ResourceType.Document, OperationType.Read, (opt, e2ecfg, clientCtxOverride) -> readDocumentCore(documentLink, opt, e2ecfg, clientCtxOverride), options, false, innerDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> readDocumentCore( String documentLink, RequestOptions options, CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, DiagnosticsClientContext clientContextOverride) { RequestOptions nonNullRequestOptions = options != null ? options : new RequestOptions(); ScopedDiagnosticsFactory scopedDiagnosticsFactory = new ScopedDiagnosticsFactory(clientContextOverride, false); DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(scopedDiagnosticsFactory); return getPointOperationResponseMonoWithE2ETimeout( nonNullRequestOptions, endToEndPolicyConfig, ObservableHelper.inlineIfPossibleAsObs( () -> readDocumentInternal( documentLink, nonNullRequestOptions, retryPolicyInstance, scopedDiagnosticsFactory), retryPolicyInstance), scopedDiagnosticsFactory ); } private Mono<ResourceResponse<Document>> readDocumentInternal( String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance, DiagnosticsClientContext clientContextOverride) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( getEffectiveClientContext(clientContextOverride), OperationType.Read, ResourceType.Document, path, requestHeaders, options); options.getMarkE2ETimeoutInRequestContextCallbackHook().set( () -> request.requestContext.setIsRequestCancelledOnTimeout(new AtomicBoolean(true))); request.requestContext.setExcludeRegions(options.getExcludeRegions()); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this.read(request, retryPolicyInstance) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, QueryFeedOperationState state, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", state, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, QueryFeedOperationState state, Class<T> klass) { final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(this, true); state.registerDiagnosticsFactory( () -> {}, (ctx) -> diagnosticsFactory.merge(ctx) ); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(diagnosticsFactory, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono .flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } itemIdentityList .forEach(itemIdentity -> { if (pkDefinition.getKind().equals(PartitionKind.MULTI_HASH) && ModelBridgeInternal.getPartitionKeyInternal(itemIdentity.getPartitionKey()) .getComponents().size() != pkDefinition.getPaths().size()) { throw new IllegalArgumentException(RMResources.PartitionKeyMismatch); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); Flux<FeedResponse<T>> pointReads = pointReadsForReadMany( diagnosticsFactory, partitionRangeItemKeyMap, resourceLink, state.getQueryOptions(), klass); Flux<FeedResponse<T>> queries = queryForReadMany( diagnosticsFactory, resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), state.getQueryOptions(), klass, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)); return Flux.merge(pointReads, queries) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); Collection<ClientSideRequestStatistics> aggregateRequestStatistics = new DistinctClientSideRequestStatisticsCollection(); double requestCharge = 0; for (FeedResponse<T> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults()); aggregateRequestStatistics.addAll(diagnosticsAccessor.getClientSideRequestStatistics(page.getCosmosDiagnostics())); } CosmosDiagnostics aggregatedDiagnostics = BridgeInternal.createCosmosDiagnostics(aggregatedQueryMetrics); diagnosticsAccessor.addClientSideDiagnosticsToFeed( aggregatedDiagnostics, aggregateRequestStatistics); state.mergeDiagnosticsContext(); CosmosDiagnosticsContext ctx = state.getDiagnosticsContextSnapshot(); if (ctx != null) { ctxAccessor.recordOperation( ctx, 200, 0, finalList.size(), requestCharge, aggregatedDiagnostics, null ); diagnosticsAccessor .setDiagnosticsContext( aggregatedDiagnostics, ctx); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponseWithQueryMetrics( finalList, headers, aggregatedQueryMetrics, null, false, false, aggregatedDiagnostics); return frp; }); }) .onErrorMap(throwable -> { if (throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException)throwable; CosmosDiagnostics diagnostics = cosmosException.getDiagnostics(); if (diagnostics != null) { state.mergeDiagnosticsContext(); CosmosDiagnosticsContext ctx = state.getDiagnosticsContextSnapshot(); if (ctx != null) { ctxAccessor.recordOperation( ctx, cosmosException.getStatusCode(), cosmosException.getSubStatusCode(), 0, cosmosException.getRequestCharge(), diagnostics, throwable ); diagnosticsAccessor .setDiagnosticsContext( diagnostics, state.getDiagnosticsContextSnapshot()); } } return cosmosException; } return throwable; }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); List<String> partitionKeySelectors = createPkSelectors(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; List<CosmosItemIdentity> cosmosItemIdentityList = entry.getValue(); if (cosmosItemIdentityList.size() > 1) { if (partitionKeySelectors.size() == 1 && partitionKeySelectors.get(0).equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(cosmosItemIdentityList); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), partitionKeySelectors); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame(List<CosmosItemIdentity> idPartitionKeyPairList) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec( List<CosmosItemIdentity> itemIdentities, List<String> partitionKeySelectors) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); int paramCount = 0; for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object[] pkValues = ModelBridgeInternal.getPartitionKeyInternal(pkValueAsPartitionKey).toObjectArray(); List<List<String>> partitionKeyParams = new ArrayList<>(); int pathCount = 0; for (Object pkComponentValue : pkValues) { String pkParamName = "@param" + paramCount; partitionKeyParams.add(Arrays.asList(partitionKeySelectors.get(pathCount), pkParamName)); parameters.add(new SqlParameter(pkParamName, pkComponentValue)); paramCount++; pathCount++; } String idValue = itemIdentity.getId(); String idParamName = "@param" + paramCount; paramCount++; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); for (List<String> pkParam: partitionKeyParams) { queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(pkParam.get(0)); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParam.get(1)); } queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private List<String> createPkSelectors(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.toList()); } private <T> Flux<FeedResponse<T>> queryForReadMany( ScopedDiagnosticsFactory diagnosticsFactory, String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { if (rangeQueryMap.isEmpty()) { return Flux.empty(); } UUID activityId = randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync( diagnosticsFactory, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum, isQueryCancelledOnTimeout); Flux<FeedResponse<T>> feedResponseFlux = executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions, ResourceType.Document, OperationType.Query); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout( feedResponseFlux, endToEndPolicyConfig, options, isQueryCancelledOnTimeout, diagnosticsFactory); } return feedResponseFlux; } private <T> Flux<FeedResponse<T>> pointReadsForReadMany( ScopedDiagnosticsFactory diagnosticsFactory, Map<PartitionKeyRange, List<CosmosItemIdentity>> singleItemPartitionRequestMap, String resourceLink, CosmosQueryRequestOptions queryRequestOptions, Class<T> klass) { ItemDeserializer effectiveItemDeserializer = getEffectiveItemDeserializer(queryRequestOptions, klass); return Flux.fromIterable(singleItemPartitionRequestMap.values()) .flatMap(cosmosItemIdentityList -> { if (cosmosItemIdentityList.size() == 1) { CosmosItemIdentity firstIdentity = cosmosItemIdentityList.get(0); RequestOptions requestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(queryRequestOptions); requestOptions.setPartitionKey(firstIdentity.getPartitionKey()); return this.readDocument((resourceLink + firstIdentity.getId()), requestOptions, diagnosticsFactory) .flatMap(resourceResponse -> Mono.just( new ImmutablePair<ResourceResponse<Document>, CosmosException>(resourceResponse, null) )) .onErrorResume(throwable -> { Throwable unwrappedThrowable = Exceptions.unwrap(throwable); if (unwrappedThrowable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) unwrappedThrowable; int statusCode = cosmosException.getStatusCode(); int subStatusCode = cosmosException.getSubStatusCode(); if (statusCode == HttpConstants.StatusCodes.NOTFOUND && subStatusCode == HttpConstants.SubStatusCodes.UNKNOWN) { return Mono.just(new ImmutablePair<ResourceResponse<Document>, CosmosException>(null, cosmosException)); } } return Mono.error(unwrappedThrowable); }); } return Mono.empty(); }) .flatMap(resourceResponseToExceptionPair -> { ResourceResponse<Document> resourceResponse = resourceResponseToExceptionPair.getLeft(); CosmosException cosmosException = resourceResponseToExceptionPair.getRight(); FeedResponse<T> feedResponse; if (cosmosException != null) { feedResponse = ModelBridgeInternal.createFeedResponse(new ArrayList<>(), cosmosException.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosException.getDiagnostics()))); } else { CosmosItemResponse<T> cosmosItemResponse = ModelBridgeInternal.createCosmosAsyncItemResponse(resourceResponse, klass, effectiveItemDeserializer); feedResponse = ModelBridgeInternal.createFeedResponse( Arrays.asList(cosmosItemResponse.getItem()), cosmosItemResponse.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosItemResponse.getDiagnostics()))); } return Mono.just(feedResponse); }); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, QueryFeedOperationState state, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), state, classOfT); } private <T> ItemDeserializer getEffectiveItemDeserializer( CosmosQueryRequestOptions queryRequestOptions, Class<T> klass) { Function<JsonNode, T> factoryMethod = queryRequestOptions == null ? null : qryOptAccessor.getImpl(queryRequestOptions).getItemFactoryMethod(klass); if (factoryMethod == null) { return this.itemDeserializer; } return new ItemDeserializer.JsonDeserializer(factoryMethod); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public <T> Mono<T> executeFeedOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, Supplier<DocumentClientRetryPolicy> retryPolicyFactory, RxDocumentServiceRequest req, BiFunction<Supplier<DocumentClientRetryPolicy>, RxDocumentServiceRequest, Mono<T>> feedOperation) { return RxDocumentClientImpl.this.executeFeedOperationWithAvailabilityStrategy( resourceType, operationType, retryPolicyFactory, req, feedOperation ); } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, state, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeedFromPagedFlux(DocumentCollection collection, ChangeFeedOperationState state, Class<T> classOfT) { return queryDocumentChangeFeed(collection, state.getChangeFeedOptions(), classOfT); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, QueryFeedOperationState state, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } final CosmosQueryRequestOptions effectiveOptions = qryOptAccessor.clone(state.getQueryOptions()); RequestOptions nonNullRequestOptions = qryOptAccessor.toRequestOptions(effectiveOptions); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = nonNullRequestOptions.getCosmosEndToEndLatencyPolicyConfig(); List<String> orderedApplicableRegionsForSpeculation = getApplicableRegionsForSpeculation( endToEndPolicyConfig, ResourceType.Document, OperationType.Query, false, nonNullRequestOptions); ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(this, false); if (orderedApplicableRegionsForSpeculation.size() < 2) { state.registerDiagnosticsFactory( () -> {}, (ctx) -> diagnosticsFactory.merge(ctx)); } else { state.registerDiagnosticsFactory( () -> diagnosticsFactory.reset(), (ctx) -> diagnosticsFactory.merge(ctx)); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create( diagnosticsFactory, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); List<String> partitionKeySelectors = createPkSelectors(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, partitionKeySelectors); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = randomUuid(); final AtomicBoolean isQueryCancelledOnTimeout = new AtomicBoolean(false); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(state.getQueryOptions())); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); Flux<FeedResponse<T>> innerFlux = ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( diagnosticsFactory, resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId, isQueryCancelledOnTimeout); }); }, invalidPartitionExceptionRetryPolicy); if (orderedApplicableRegionsForSpeculation.size() < 2) { return innerFlux; } return innerFlux .flatMap(result -> { diagnosticsFactory.merge(nonNullRequestOptions); return Mono.just(result); }) .onErrorMap(throwable -> { diagnosticsFactory.merge(nonNullRequestOptions); return throwable; }) .doOnCancel(() -> diagnosticsFactory.merge(nonNullRequestOptions)); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, QueryFeedOperationState state) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (options != null) { request.requestContext.setExcludeRegions(options.getExcludeRegions()); } if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, QueryFeedOperationState state) { return queryTriggers(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions( String collectionLink, String query, QueryFeedOperationState state) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions( String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return nonDocumentReadFeed(state, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, QueryFeedOperationState state) { return queryConflicts(collectionLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(collectionLink, querySpec, state, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, QueryFeedOperationState state) { return queryUsers(databaseLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys( String databaseLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return nonDocumentReadFeed(state, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys( String databaseLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(databaseLink, querySpec, state, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy(null)); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); return RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, QueryFeedOperationState state) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return nonDocumentReadFeed(state, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, QueryFeedOperationState state) { return queryPermissions(userLink, new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(userLink, querySpec, state, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(QueryFeedOperationState state) { return nonDocumentReadFeed(state, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeed( QueryFeedOperationState state, ResourceType resourceType, Class<T> klass, String resourceLink) { return nonDocumentReadFeed(state.getQueryOptions(), resourceType, klass, resourceLink); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> nonDocumentReadFeedInternal(options, resourceType, klass, resourceLink, retryPolicy), retryPolicy); } private <T> Flux<FeedResponse<T>> nonDocumentReadFeedInternal( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink, DocumentClientRetryPolicy retryPolicy) { final CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions(); Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(nonNullOptions); int maxPageSize = maxItemCount != null ? maxItemCount : -1; assert(resourceType != ResourceType.Document); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, nonNullOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> readFeed(request) .map(response -> toFeedResponsePage( response, qryOptAccessor.getImpl(nonNullOptions).getItemFactoryMethod(klass), klass)); return Paginator .getPaginatedQueryResultAsObservable( nonNullOptions, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, QueryFeedOperationState state) { return queryOffers(new SqlQuerySpec(query), state); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, QueryFeedOperationState state) { return createQuery(null, querySpec, state, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(null); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } @Override public GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } @Override public AddressSelector getAddressSelector() { return new AddressSelector(this.addressResolver, this.configs.getProtocol()); } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.useGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); if (ConnectionMode.DIRECT == this.connectionPolicy.getConnectionMode()) { this.storeModel.enableThroughputControl(throughputControlStore); } else { this.gatewayProxy.enableThroughputControl(throughputControlStore); } } this.throughputControlStore.enableThroughputControlGroup(group, throughputQueryMono); } @Override public Flux<Void> submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig) { return this.storeModel.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig); } @Override public ConsistencyLevel getDefaultConsistencyLevelOfAccount() { return this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } /*** * Configure fault injector provider. * * @param injectorProvider the fault injector provider. */ @Override public void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) { checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null"); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.DIRECT) { this.storeModel.configureFaultInjectorProvider(injectorProvider, this.configs); this.addressResolver.configureFaultInjectorProvider(injectorProvider, this.configs); } this.gatewayProxy.configureFaultInjectorProvider(injectorProvider, this.configs); } @Override public void recordOpenConnectionsAndInitCachesCompleted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesCompleted(cosmosContainerIdentities); } @Override public void recordOpenConnectionsAndInitCachesStarted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesStarted(cosmosContainerIdentities); } @Override public String getMasterKeyOrResourceToken() { return this.masterKeyOrResourceToken; } private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, List<String> partitionKeySelectors) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object[] pkValues = ModelBridgeInternal.getPartitionKeyInternal(partitionKey).toObjectArray(); String pkParamNamePrefix = "@pkValue"; for (int i = 0; i < pkValues.length; i++) { StringBuilder subQueryStringBuilder = new StringBuilder(); String sqlParameterName = pkParamNamePrefix + i; if (i > 0) { subQueryStringBuilder.append(" AND "); } subQueryStringBuilder.append(" c"); subQueryStringBuilder.append(partitionKeySelectors.get(i)); subQueryStringBuilder.append((" = ")); subQueryStringBuilder.append(sqlParameterName); parameters.add(new SqlParameter(sqlParameterName, pkValues[i])); queryStringBuilder.append(subQueryStringBuilder); } return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink, boolean forceRefresh) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink, forceRefresh), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal( RxDocumentServiceRequest request, String collectionLink, boolean forceRefresh) { logger.debug("getFeedRange collectionLink=[{}] - forceRefresh={}", collectionLink, forceRefresh); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, forceRefresh, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } /** * Creates a type 4 (pseudo randomly generated) UUID. * <p> * The {@link UUID} is generated using a non-cryptographically strong pseudo random number generator. * * @return A randomly generated {@link UUID}. */ public static UUID randomUuid() { return randomUuid(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); } static UUID randomUuid(long msb, long lsb) { msb &= 0xffffffffffff0fffL; msb |= 0x0000000000004000L; lsb &= 0x3fffffffffffffffL; lsb |= 0x8000000000000000L; return new UUID(msb, lsb); } private Mono<ResourceResponse<Document>> wrapPointOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, DocumentPointOperation callback, RequestOptions initialRequestOptions, boolean idempotentWriteRetriesEnabled) { return wrapPointOperationWithAvailabilityStrategy( resourceType, operationType, callback, initialRequestOptions, idempotentWriteRetriesEnabled, this ); } private Mono<ResourceResponse<Document>> wrapPointOperationWithAvailabilityStrategy( ResourceType resourceType, OperationType operationType, DocumentPointOperation callback, RequestOptions initialRequestOptions, boolean idempotentWriteRetriesEnabled, DiagnosticsClientContext innerDiagnosticsFactory) { checkNotNull(resourceType, "Argument 'resourceType' must not be null."); checkNotNull(operationType, "Argument 'operationType' must not be null."); checkNotNull(callback, "Argument 'callback' must not be null."); final RequestOptions nonNullRequestOptions = initialRequestOptions != null ? initialRequestOptions : new RequestOptions(); checkArgument( resourceType == ResourceType.Document, "This method can only be used for document point operations."); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(nonNullRequestOptions, resourceType, operationType); List<String> orderedApplicableRegionsForSpeculation = getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, idempotentWriteRetriesEnabled, nonNullRequestOptions); if (orderedApplicableRegionsForSpeculation.size() < 2) { return callback.apply(nonNullRequestOptions, endToEndPolicyConfig, innerDiagnosticsFactory); } ThresholdBasedAvailabilityStrategy availabilityStrategy = (ThresholdBasedAvailabilityStrategy)endToEndPolicyConfig.getAvailabilityStrategy(); List<Mono<NonTransientPointOperationResult>> monoList = new ArrayList<>(); final ScopedDiagnosticsFactory diagnosticsFactory = new ScopedDiagnosticsFactory(innerDiagnosticsFactory, false); orderedApplicableRegionsForSpeculation .forEach(region -> { RequestOptions clonedOptions = new RequestOptions(nonNullRequestOptions); if (monoList.isEmpty()) { Mono<NonTransientPointOperationResult> initialMonoAcrossAllRegions = callback.apply(clonedOptions, endToEndPolicyConfig, diagnosticsFactory) .map(NonTransientPointOperationResult::new) .onErrorResume( RxDocumentClientImpl::isCosmosException, t -> Mono.just( new NonTransientPointOperationResult( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); if (logger.isDebugEnabled()) { monoList.add(initialMonoAcrossAllRegions.doOnSubscribe(c -> logger.debug( "STARTING to process {} operation in region '{}'", operationType, region))); } else { monoList.add(initialMonoAcrossAllRegions); } } else { clonedOptions.setExcludeRegions( getEffectiveExcludedRegionsForHedging( nonNullRequestOptions.getExcludeRegions(), orderedApplicableRegionsForSpeculation, region) ); Mono<NonTransientPointOperationResult> regionalCrossRegionRetryMono = callback.apply(clonedOptions, endToEndPolicyConfig, diagnosticsFactory) .map(NonTransientPointOperationResult::new) .onErrorResume( RxDocumentClientImpl::isNonTransientCosmosException, t -> Mono.just( new NonTransientPointOperationResult( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); Duration delayForCrossRegionalRetry = (availabilityStrategy) .getThreshold() .plus((availabilityStrategy) .getThresholdStep() .multipliedBy(monoList.size() - 1)); if (logger.isDebugEnabled()) { monoList.add( regionalCrossRegionRetryMono .doOnSubscribe(c -> logger.debug("STARTING to process {} operation in region '{}'", operationType, region)) .delaySubscription(delayForCrossRegionalRetry)); } else { monoList.add( regionalCrossRegionRetryMono .delaySubscription(delayForCrossRegionalRetry)); } } }); return Mono .firstWithValue(monoList) .flatMap(nonTransientResult -> { diagnosticsFactory.merge(nonNullRequestOptions); if (nonTransientResult.isError()) { return Mono.error(nonTransientResult.exception); } return Mono.just(nonTransientResult.response); }) .onErrorMap(throwable -> { Throwable exception = Exceptions.unwrap(throwable); if (exception instanceof NoSuchElementException) { List<Throwable> innerThrowables = Exceptions .unwrapMultiple(exception.getCause()); int index = 0; for (Throwable innerThrowable : innerThrowables) { Throwable innerException = Exceptions.unwrap(innerThrowable); if (innerException instanceof CosmosException) { CosmosException cosmosException = Utils.as(innerException, CosmosException.class); diagnosticsFactory.merge(nonNullRequestOptions); return cosmosException; } else if (innerException instanceof NoSuchElementException) { logger.trace( "Operation in {} completed with empty result because it was cancelled.", orderedApplicableRegionsForSpeculation.get(index)); } else if (logger.isWarnEnabled()) { String message = "Unexpected Non-CosmosException when processing operation in '" + orderedApplicableRegionsForSpeculation.get(index) + "'."; logger.warn( message, innerException ); } index++; } } diagnosticsFactory.merge(nonNullRequestOptions); return exception; }) .doOnCancel(() -> diagnosticsFactory.merge(nonNullRequestOptions)); } private static boolean isCosmosException(Throwable t) { final Throwable unwrappedException = Exceptions.unwrap(t); return unwrappedException instanceof CosmosException; } private static boolean isNonTransientCosmosException(Throwable t) { final Throwable unwrappedException = Exceptions.unwrap(t); if (!(unwrappedException instanceof CosmosException)) { return false; } CosmosException cosmosException = Utils.as(unwrappedException, CosmosException.class); return isNonTransientResultForHedging( cosmosException.getStatusCode(), cosmosException.getSubStatusCode()); } private List<String> getEffectiveExcludedRegionsForHedging( List<String> initialExcludedRegions, List<String> applicableRegions, String currentRegion) { List<String> effectiveExcludedRegions = new ArrayList<>(); if (initialExcludedRegions != null) { effectiveExcludedRegions.addAll(initialExcludedRegions); } for (String applicableRegion: applicableRegions) { if (!applicableRegion.equals(currentRegion)) { effectiveExcludedRegions.add(applicableRegion); } } return effectiveExcludedRegions; } private static boolean isNonTransientResultForHedging(int statusCode, int subStatusCode) { if (statusCode < HttpConstants.StatusCodes.BADREQUEST) { return true; } if (statusCode == HttpConstants.StatusCodes.REQUEST_TIMEOUT && subStatusCode == HttpConstants.SubStatusCodes.CLIENT_OPERATION_TIMEOUT) { return true; } if (statusCode == HttpConstants.StatusCodes.BADREQUEST || statusCode == HttpConstants.StatusCodes.CONFLICT || statusCode == HttpConstants.StatusCodes.METHOD_NOT_ALLOWED || statusCode == HttpConstants.StatusCodes.PRECONDITION_FAILED || statusCode == HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE || statusCode == HttpConstants.StatusCodes.UNAUTHORIZED) { return true; } if (statusCode == HttpConstants.StatusCodes.NOTFOUND && subStatusCode == HttpConstants.SubStatusCodes.UNKNOWN) { return true; } return false; } private DiagnosticsClientContext getEffectiveClientContext(DiagnosticsClientContext clientContextOverride) { if (clientContextOverride != null) { return clientContextOverride; } return this; } /** * Returns the applicable endpoints ordered by preference list if any * @param operationType - the operationT * @return the applicable endpoints ordered by preference list if any */ private List<URI> getApplicableEndPoints(OperationType operationType, List<String> excludedRegions) { if (operationType.isReadOnlyOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableReadEndpoints(excludedRegions)); } else if (operationType.isWriteOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableWriteEndpoints(excludedRegions)); } return EMPTY_ENDPOINT_LIST; } private static List<URI> withoutNulls(List<URI> orderedEffectiveEndpointsList) { if (orderedEffectiveEndpointsList == null) { return EMPTY_ENDPOINT_LIST; } int i = 0; while (i < orderedEffectiveEndpointsList.size()) { if (orderedEffectiveEndpointsList.get(i) == null) { orderedEffectiveEndpointsList.remove(i); } else { i++; } } return orderedEffectiveEndpointsList; } private List<String> getApplicableRegionsForSpeculation( CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, ResourceType resourceType, OperationType operationType, boolean isIdempotentWriteRetriesEnabled, RequestOptions options) { return getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, isIdempotentWriteRetriesEnabled, options.getExcludeRegions()); } private List<String> getApplicableRegionsForSpeculation( CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig, ResourceType resourceType, OperationType operationType, boolean isIdempotentWriteRetriesEnabled, List<String> excludedRegions) { if (endToEndPolicyConfig == null || !endToEndPolicyConfig.isEnabled()) { return EMPTY_REGION_LIST; } if (resourceType != ResourceType.Document) { return EMPTY_REGION_LIST; } if (operationType.isWriteOperation() && !isIdempotentWriteRetriesEnabled) { return EMPTY_REGION_LIST; } if (operationType.isWriteOperation() && !this.globalEndpointManager.canUseMultipleWriteLocations()) { return EMPTY_REGION_LIST; } if (!(endToEndPolicyConfig.getAvailabilityStrategy() instanceof ThresholdBasedAvailabilityStrategy)) { return EMPTY_REGION_LIST; } List<URI> endpoints = getApplicableEndPoints(operationType, excludedRegions); HashSet<String> normalizedExcludedRegions = new HashSet<>(); if (excludedRegions != null) { excludedRegions.forEach(r -> normalizedExcludedRegions.add(r.toLowerCase(Locale.ROOT))); } List<String> orderedRegionsForSpeculation = new ArrayList<>(); endpoints.forEach(uri -> { String regionName = this.globalEndpointManager.getRegionName(uri, operationType); if (!normalizedExcludedRegions.contains(regionName.toLowerCase(Locale.ROOT))) { orderedRegionsForSpeculation.add(regionName); } }); return orderedRegionsForSpeculation; } private <T> Mono<T> executeFeedOperationWithAvailabilityStrategy( final ResourceType resourceType, final OperationType operationType, final Supplier<DocumentClientRetryPolicy> retryPolicyFactory, final RxDocumentServiceRequest req, final BiFunction<Supplier<DocumentClientRetryPolicy>, RxDocumentServiceRequest, Mono<T>> feedOperation ) { checkNotNull(retryPolicyFactory, "Argument 'retryPolicyFactory' must not be null."); checkNotNull(req, "Argument 'req' must not be null."); assert(resourceType == ResourceType.Document); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = this.getEffectiveEndToEndOperationLatencyPolicyConfig( req.requestContext.getEndToEndOperationLatencyPolicyConfig(), resourceType, operationType); List<String> initialExcludedRegions = req.requestContext.getExcludeRegions(); List<String> orderedApplicableRegionsForSpeculation = this.getApplicableRegionsForSpeculation( endToEndPolicyConfig, resourceType, operationType, false, initialExcludedRegions ); if (orderedApplicableRegionsForSpeculation.size() < 2) { return feedOperation.apply(retryPolicyFactory, req); } ThresholdBasedAvailabilityStrategy availabilityStrategy = (ThresholdBasedAvailabilityStrategy)endToEndPolicyConfig.getAvailabilityStrategy(); List<Mono<NonTransientFeedOperationResult<T>>> monoList = new ArrayList<>(); orderedApplicableRegionsForSpeculation .forEach(region -> { RxDocumentServiceRequest clonedRequest = req.clone(); if (monoList.isEmpty()) { Mono<NonTransientFeedOperationResult<T>> initialMonoAcrossAllRegions = feedOperation.apply(retryPolicyFactory, clonedRequest) .map(NonTransientFeedOperationResult::new) .onErrorResume( RxDocumentClientImpl::isCosmosException, t -> Mono.just( new NonTransientFeedOperationResult<>( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); if (logger.isDebugEnabled()) { monoList.add(initialMonoAcrossAllRegions.doOnSubscribe(c -> logger.debug( "STARTING to process {} operation in region '{}'", operationType, region))); } else { monoList.add(initialMonoAcrossAllRegions); } } else { clonedRequest.requestContext.setExcludeRegions( getEffectiveExcludedRegionsForHedging( initialExcludedRegions, orderedApplicableRegionsForSpeculation, region) ); Mono<NonTransientFeedOperationResult<T>> regionalCrossRegionRetryMono = feedOperation.apply(retryPolicyFactory, clonedRequest) .map(NonTransientFeedOperationResult::new) .onErrorResume( RxDocumentClientImpl::isNonTransientCosmosException, t -> Mono.just( new NonTransientFeedOperationResult<>( Utils.as(Exceptions.unwrap(t), CosmosException.class)))); Duration delayForCrossRegionalRetry = (availabilityStrategy) .getThreshold() .plus((availabilityStrategy) .getThresholdStep() .multipliedBy(monoList.size() - 1)); if (logger.isDebugEnabled()) { monoList.add( regionalCrossRegionRetryMono .doOnSubscribe(c -> logger.debug("STARTING to process {} operation in region '{}'", operationType, region)) .delaySubscription(delayForCrossRegionalRetry)); } else { monoList.add( regionalCrossRegionRetryMono .delaySubscription(delayForCrossRegionalRetry)); } } }); return Mono .firstWithValue(monoList) .flatMap(nonTransientResult -> { if (nonTransientResult.isError()) { return Mono.error(nonTransientResult.exception); } return Mono.just(nonTransientResult.response); }) .onErrorMap(throwable -> { Throwable exception = Exceptions.unwrap(throwable); if (exception instanceof NoSuchElementException) { List<Throwable> innerThrowables = Exceptions .unwrapMultiple(exception.getCause()); int index = 0; for (Throwable innerThrowable : innerThrowables) { Throwable innerException = Exceptions.unwrap(innerThrowable); if (innerException instanceof CosmosException) { return Utils.as(innerException, CosmosException.class); } else if (innerException instanceof NoSuchElementException) { logger.trace( "Operation in {} completed with empty result because it was cancelled.", orderedApplicableRegionsForSpeculation.get(index)); } else if (logger.isWarnEnabled()) { String message = "Unexpected Non-CosmosException when processing operation in '" + orderedApplicableRegionsForSpeculation.get(index) + "'."; logger.warn( message, innerException ); } index++; } } return exception; }); } @FunctionalInterface private interface DocumentPointOperation { Mono<ResourceResponse<Document>> apply(RequestOptions requestOptions, CosmosEndToEndOperationLatencyPolicyConfig endToEndOperationLatencyPolicyConfig, DiagnosticsClientContext clientContextOverride); } private static class NonTransientPointOperationResult { private final ResourceResponse<Document> response; private final CosmosException exception; public NonTransientPointOperationResult(CosmosException exception) { checkNotNull(exception, "Argument 'exception' must not be null."); this.exception = exception; this.response = null; } public NonTransientPointOperationResult(ResourceResponse<Document> response) { checkNotNull(response, "Argument 'response' must not be null."); this.exception = null; this.response = response; } public boolean isError() { return this.exception != null; } public CosmosException getException() { return this.exception; } public ResourceResponse<Document> getResponse() { return this.response; } } private static class NonTransientFeedOperationResult<T> { private final T response; private final CosmosException exception; public NonTransientFeedOperationResult(CosmosException exception) { checkNotNull(exception, "Argument 'exception' must not be null."); this.exception = exception; this.response = null; } public NonTransientFeedOperationResult(T response) { checkNotNull(response, "Argument 'response' must not be null."); this.exception = null; this.response = response; } public boolean isError() { return this.exception != null; } public CosmosException getException() { return this.exception; } public T getResponse() { return this.response; } } private static class ScopedDiagnosticsFactory implements DiagnosticsClientContext { private final AtomicBoolean isMerged = new AtomicBoolean(false); private final DiagnosticsClientContext inner; private final ConcurrentLinkedQueue<CosmosDiagnostics> createdDiagnostics; private final boolean shouldCaptureAllFeedDiagnostics; private final AtomicReference<CosmosDiagnostics> mostRecentlyCreatedDiagnostics = new AtomicReference<>(null); public ScopedDiagnosticsFactory(DiagnosticsClientContext inner, boolean shouldCaptureAllFeedDiagnostics) { checkNotNull(inner, "Argument 'inner' must not be null."); this.inner = inner; this.createdDiagnostics = new ConcurrentLinkedQueue<>(); this.shouldCaptureAllFeedDiagnostics = shouldCaptureAllFeedDiagnostics; } @Override public DiagnosticsClientConfig getConfig() { return inner.getConfig(); } @Override public CosmosDiagnostics createDiagnostics() { CosmosDiagnostics diagnostics = inner.createDiagnostics(); createdDiagnostics.add(diagnostics); mostRecentlyCreatedDiagnostics.set(diagnostics); return diagnostics; } @Override public String getUserAgent() { return inner.getUserAgent(); } @Override public CosmosDiagnostics getMostRecentlyCreatedDiagnostics() { return this.mostRecentlyCreatedDiagnostics.get(); } public void merge(RequestOptions requestOptions) { CosmosDiagnosticsContext knownCtx = null; if (requestOptions != null) { CosmosDiagnosticsContext ctxSnapshot = requestOptions.getDiagnosticsContextSnapshot(); if (ctxSnapshot != null) { knownCtx = requestOptions.getDiagnosticsContextSnapshot(); } } merge(knownCtx); } public void merge(CosmosDiagnosticsContext knownCtx) { if (!isMerged.compareAndSet(false, true)) { return; } CosmosDiagnosticsContext ctx = null; if (knownCtx != null) { ctx = knownCtx; } else { for (CosmosDiagnostics diagnostics : this.createdDiagnostics) { if (diagnostics.getDiagnosticsContext() != null) { ctx = diagnostics.getDiagnosticsContext(); break; } } } if (ctx == null) { return; } for (CosmosDiagnostics diagnostics : this.createdDiagnostics) { if (diagnostics.getDiagnosticsContext() == null && diagnosticsAccessor.isNotEmpty(diagnostics)) { if (this.shouldCaptureAllFeedDiagnostics && diagnosticsAccessor.getFeedResponseDiagnostics(diagnostics) != null) { AtomicBoolean isCaptured = diagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(diagnostics); if (isCaptured != null) { isCaptured.set(true); } } ctxAccessor.addDiagnostics(ctx, diagnostics); } } } public void reset() { this.createdDiagnostics.clear(); this.isMerged.set(false); } } }
Fixed
private Flux<CosmosBulkOperationResponse<TContext>> executeCore() { Integer nullableMaxConcurrentCosmosPartitions = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxConcurrentCosmosPartitions(cosmosBulkExecutionOptions); Mono<Integer> maxConcurrentCosmosPartitionsMono = nullableMaxConcurrentCosmosPartitions != null ? Mono.just(Math.max(256, nullableMaxConcurrentCosmosPartitions)) : ImplementationBridgeHelpers .CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getFeedRanges(this.container, false).map(ranges -> Math.max(256, ranges.size() * 2)); return maxConcurrentCosmosPartitionsMono .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMapMany(maxConcurrentCosmosPartitions -> { logDebugOrWarning("BulkExecutor.execute with MaxConcurrentPartitions: {}, Context: {}", maxConcurrentCosmosPartitions, this.operationContextText); return this.inputOperations .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .onErrorMap(throwable -> { logger.error("{}: Skipping an error operation while processing. Cause: {}, Context: {}", Thread.currentThread ().getName(), throwable.getMessage(), this.operationContextText, throwable); return throwable; }) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } logger.trace( "SetupRetryPolicy, {}, TotalCount: {}, Context: {}, {}", getItemOperationDiagnostics(cosmosItemOperation), totalCount.get(), this.operationContextText, getThreadInfo() ); }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logDebugOrWarning("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.cancelFlushTask(true); this.onFlush(); logDebugOrWarning("Scheduled new flush operation {}, Context: {}", getThreadInfo(), this.operationContextText); } }) .mergeWith(mainSink.asFlux()) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap( operation -> { logger.trace("Before Resolve PkRangeId, {}, Context: {} {}", getItemOperationDiagnostics(operation), this.operationContextText, getThreadInfo()); return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); logger.trace("Resolved PkRangeId, {}, PKRangeId: {} Context: {} {}", getItemOperationDiagnostics(operation), pkRangeId, this.operationContextText, getThreadInfo()); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap( this::executePartitionedGroup, maxConcurrentCosmosPartitions) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logDebugOrWarning("All work completed, {}, TotalCount: {}, Context: {} {}", getItemOperationDiagnostics(requestAndResponse.getOperation()), totalCountAfterDecrement, this.operationContextText, getThreadInfo()); completeAllSinks(); } else { if (totalCountAfterDecrement == 0) { logDebugOrWarning( "No Work left - but mainSource not yet completed, Context: {} {}", this.operationContextText, getThreadInfo()); } logger.trace( "Work left - TotalCount after decrement: {}, main sink completed {}, {}, Context: {} {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, getItemOperationDiagnostics(requestAndResponse.getOperation()), this.operationContextText, getThreadInfo()); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logDebugOrWarning("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logDebugOrWarning( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {} {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText, getThreadInfo()); } }); }); }
Thread.currentThread ().getName(),
default concurrency (256), Integer nullableMaxConcurrentCosmosPartitions = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxConcurrentCosmosPartitions(cosmosBulkExecutionOptions); Mono<Integer> maxConcurrentCosmosPartitionsMono = nullableMaxConcurrentCosmosPartitions != null ? Mono.just(Math.max(256, nullableMaxConcurrentCosmosPartitions)) : ImplementationBridgeHelpers .CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getFeedRanges(this.container, false).map(ranges -> Math.max(256, ranges.size() * 2)); return maxConcurrentCosmosPartitionsMono .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMapMany(maxConcurrentCosmosPartitions -> { logDebugOrWarning("BulkExecutor.execute with MaxConcurrentPartitions: {}, Context: {}", maxConcurrentCosmosPartitions, this.operationContextText); return this.inputOperations .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .onErrorMap(throwable -> { logger.error("{}: Skipping an error operation while processing. Cause: {}, Context: {}", getThreadInfo(), throwable.getMessage(), this.operationContextText, throwable); return throwable; }) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } logger.trace( "SetupRetryPolicy, {}, TotalCount: {}, Context: {}, {}", getItemOperationDiagnostics(cosmosItemOperation), totalCount.get(), this.operationContextText, getThreadInfo() ); }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logDebugOrWarning("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.cancelFlushTask(true); this.onFlush(); logDebugOrWarning("Scheduled new flush operation {}, Context: {}", getThreadInfo(), this.operationContextText); } }) .mergeWith(mainSink.asFlux()) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap( operation -> { logger.trace("Before Resolve PkRangeId, {}, Context: {} {}", getItemOperationDiagnostics(operation), this.operationContextText, getThreadInfo()); return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); logger.trace("Resolved PkRangeId, {}, PKRangeId: {} Context: {} {}", getItemOperationDiagnostics(operation), pkRangeId, this.operationContextText, getThreadInfo()); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap( this::executePartitionedGroup, maxConcurrentCosmosPartitions) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logDebugOrWarning("All work completed, {}, TotalCount: {}, Context: {} {}", getItemOperationDiagnostics(requestAndResponse.getOperation()), totalCountAfterDecrement, this.operationContextText, getThreadInfo()); completeAllSinks(); } else { if (totalCountAfterDecrement == 0) { logDebugOrWarning( "No Work left - but mainSource not yet completed, Context: {} {}", this.operationContextText, getThreadInfo()); } logger.trace( "Work left - TotalCount after decrement: {}, main sink completed {}, {}, Context: {} {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, getItemOperationDiagnostics(requestAndResponse.getOperation()), this.operationContextText, getThreadInfo()); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logDebugOrWarning("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logDebugOrWarning( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {} {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText, getThreadInfo()); } }); }
class BulkExecutor<TContext> implements Disposable { private final static ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper.CosmosBulkExecutionOptionsAccessor bulkOptionsAccessor = ImplementationBridgeHelpers .CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor(); private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private static final ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor clientAccessor = ImplementationBridgeHelpers.CosmosAsyncClientHelper.getCosmosAsyncClientAccessor(); private final CosmosAsyncContainer container; private final int maxMicroBatchPayloadSizeInBytes; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicBoolean isDisposed = new AtomicBoolean(false); private final AtomicBoolean isShutdown = new AtomicBoolean(false); private final AtomicInteger totalCount; private final static Sinks.EmitFailureHandler serializedEmitFailureHandler = new SerializedEmitFailureHandler(); private final static Sinks.EmitFailureHandler serializedCompleteEmitFailureHandler = new SerializedCompleteEmitFailureHandler();; private final Sinks.Many<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final CosmosAsyncClient cosmosClient; private final String bulkSpanName; private final AtomicReference<Disposable> scheduledFutureForFlush; private final String identifier = "BulkExecutor-" + instanceCount.incrementAndGet(); private final BulkExecutorDiagnosticsTracker diagnosticsTracker; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.maxMicroBatchPayloadSizeInBytes = bulkOptionsAccessor .getMaxMicroBatchPayloadSizeInBytes(cosmosBulkOptions); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.bulkSpanName = "nonTransactionalBatch." + this.container.getId(); this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.cosmosClient = ImplementationBridgeHelpers .CosmosAsyncDatabaseHelper .getCosmosAsyncDatabaseAccessor() .getCosmosAsyncClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = bulkOptionsAccessor .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = bulkOptionsAccessor .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = bulkOptionsAccessor .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = identifier + "[" + operationListener.getOperationContext().toString() + "]"; } else { operationContextText = identifier +"[n/a]"; } this.diagnosticsTracker = bulkOptionsAccessor.getDiagnosticsTracker(cosmosBulkOptions); mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainSink = Sinks.many().unicast().onBackpressureBuffer(); groupSinks = new CopyOnWriteArrayList<>(); this.scheduledFutureForFlush = new AtomicReference<>(CosmosSchedulers .BULK_EXECUTOR_FLUSH_BOUNDED_ELASTIC .schedulePeriodically( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS)); logger.debug("Instantiated BulkExecutor, Context: {}", this.operationContextText); } @Override public void dispose() { if (this.isDisposed.compareAndSet(false, true)) { long totalCountSnapshot = totalCount.get(); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.shutdown(); } } } @Override public boolean isDisposed() { return this.isDisposed.get(); } private void cancelFlushTask(boolean initializeAggressiveFlush) { long flushIntervalAfterDrainingIncomingFlux = Math.min( this.maxMicroBatchIntervalInMs, BatchRequestResponseConstants .DEFAULT_MAX_MICRO_BATCH_INTERVAL_AFTER_DRAINING_INCOMING_FLUX_IN_MILLISECONDS); Disposable newFlushTask = initializeAggressiveFlush ? CosmosSchedulers .BULK_EXECUTOR_FLUSH_BOUNDED_ELASTIC .schedulePeriodically( this::onFlush, flushIntervalAfterDrainingIncomingFlux, flushIntervalAfterDrainingIncomingFlux, TimeUnit.MILLISECONDS) : null; Disposable scheduledFutureSnapshot = this.scheduledFutureForFlush.getAndSet(newFlushTask); if (scheduledFutureSnapshot != null) { try { scheduledFutureSnapshot.dispose(); logDebugOrWarning("Cancelled all future scheduled tasks {}, Context: {}", getThreadInfo(), this.operationContextText); } catch (Exception e) { logger.warn("Failed to cancel scheduled tasks{}, Context: {}", getThreadInfo(), this.operationContextText, e); } } } private void logInfoOrWarning(String msg, Object... args) { if (this.diagnosticsTracker == null || !this.diagnosticsTracker.verboseLoggingAfterReEnqueueingRetriesEnabled()) { logger.info(msg, args); } else { logger.warn(msg, args); } } private void logDebugOrWarning(String msg, Object... args) { if (this.diagnosticsTracker == null || !this.diagnosticsTracker.verboseLoggingAfterReEnqueueingRetriesEnabled()) { logger.debug(msg, args); } else { logger.warn(msg, args); } } private void shutdown() { if (this.isShutdown.compareAndSet(false, true)) { logDebugOrWarning("Shutting down, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); this.cancelFlushTask(false); } } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this .executeCore() .doFinally((SignalType signal) -> { if (signal == SignalType.ON_COMPLETE) { logDebugOrWarning("BulkExecutor.execute flux completed - this.totalCount.get(), this.operationContextText, getThreadInfo()); } else { int itemsLeftSnapshot = this.totalCount.get(); if (itemsLeftSnapshot > 0) { logInfoOrWarning("BulkExecutor.execute flux terminated - Signal: {} - signal, itemsLeftSnapshot, this.operationContextText, getThreadInfo()); } else { logDebugOrWarning("BulkExecutor.execute flux terminated - Signal: {} - signal, itemsLeftSnapshot, this.operationContextText, getThreadInfo()); } } this.dispose(); }); } private Flux<CosmosBulkOperationResponse<TContext>> executeCore() { } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); AtomicInteger currentTotalSerializedLength = new AtomicInteger(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); logger.trace( "BufferUntil - enqueued {}, {}, Context: {} {}", timestamp, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (itemOperation == FlushBuffersItemOperation.singleton()) { long currentMicroBatchSizeSnapshot = currentMicroBatchSize.get(); if (currentMicroBatchSizeSnapshot > 0) { logger.trace( "Flushing PKRange {} (batch size: {}) due to FlushItemOperation, Context: {} {}", thresholds.getPartitionKeyRangeId(), currentMicroBatchSizeSnapshot, this.operationContextText, getThreadInfo()); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); currentTotalSerializedLength.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); int totalSerializedLength = this.calculateTotalSerializedLength(currentTotalSerializedLength, itemOperation); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs || totalSerializedLength >= this.maxMicroBatchPayloadSizeInBytes) { logDebugOrWarning( "BufferUntil - Flushing PKRange {} due to BatchSize ({}), payload size ({}) or age ({}), " + "Triggering {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), batchSize, totalSerializedLength, age, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); currentTotalSerializedLength.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } logDebugOrWarning( "Flushing PKRange {} micro batch with {} operations, Context: {} {}", thresholds.getPartitionKeyRangeId(), operations.size(), this.operationContextText, getThreadInfo()); return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private int calculateTotalSerializedLength(AtomicInteger currentTotalSerializedLength, CosmosItemOperation item) { if (item instanceof CosmosItemOperationBase) { return currentTotalSerializedLength.accumulateAndGet( ((CosmosItemOperationBase) item).getSerializedLength(), Integer::sum); } return currentTotalSerializedLength.get(); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.trace("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange, this.maxMicroBatchPayloadSizeInBytes); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMapMany(response -> { if (diagnosticsTracker != null && response.getDiagnostics() != null) { diagnosticsTracker.trackDiagnostics(response.getDiagnostics().getDiagnosticsContext()); } return Flux .fromIterable(response.getResults()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds)); }) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux .fromIterable(serverRequest.getOperations()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal .createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); logDebugOrWarning( "HandleTransactionalBatchOperationResult - PKRange {}, Response Status Code {}, " + "Operation Status Code, {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { logDebugOrWarning( "HandleTransactionalBatchOperationResult - enqueue retry, PKRange {}, Response " + "Status Code {}, Operation Status Code, {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { if (response.getStatusCode() == HttpConstants.StatusCodes.CONFLICT || response.getStatusCode() == HttpConstants.StatusCodes.PRECONDITION_FAILED) { logDebugOrWarning( "HandleTransactionalBatchOperationResult - Fail, PKRange {}, Response Status " + "Code {}, Operation Status Code {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); } else { logger.error( "HandleTransactionalBatchOperationResult - Fail, PKRange {}, Response Status " + "Code {}, Operation Status Code {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); } return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { logDebugOrWarning( "HandleTransactionalBatchExecutionException, PKRange {}, Error: {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode(), itemBulkOperation, cosmosException) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { logDebugOrWarning( "HandleTransactionalBatchExecutionException - Retry due to split, PKRange {}, Error: " + "{}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); mainSink.emitNext(itemOperation, serializedEmitFailureHandler); return Mono.empty(); } else { logDebugOrWarning( "HandleTransactionalBatchExecutionException - Retry other, PKRange {}, Error: " + "{}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setThroughputControlGroupName(cosmosBulkExecutionOptions.getThroughputControlGroupName()); options.setExcludeRegions(cosmosBulkExecutionOptions.getExcludedRegions()); Map<String, String> customOptions = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getCustomOptions(cosmosBulkExecutionOptions); if (customOptions != null && !customOptions.isEmpty()) { for(Map.Entry<String, String> entry : customOptions.entrySet()) { options.setHeader(entry.getKey(), entry.getValue()); } } options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getOperationType() == CosmosItemOperationType.READ || (itemBulkOperation.getRequestOptions() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled())) { options.setContentResponseOnWriteEnabled(true); break; } } } } return withContext(context -> { final Mono<CosmosBatchResponse> responseMono = this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); return clientAccessor.getDiagnosticsProvider(this.cosmosClient) .traceEnabledBatchResponsePublisher( responseMono, context, this.bulkSpanName, this.container.getDatabase().getId(), this.container.getId(), this.cosmosClient, options.getConsistencyLevel(), OperationType.Batch, ResourceType.Document, options); }); } private void completeAllSinks() { logInfoOrWarning("Closing all sinks, Context: {}", this.operationContextText); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.emitComplete(serializedCompleteEmitFailureHandler); this.shutdown(); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed. Context: {}", this.operationContextText, t); } } private static String getItemOperationDiagnostics(CosmosItemOperation operation) { if (operation == FlushBuffersItemOperation.singleton()) { return "ItemOperation[Type: Flush]"; } return "ItemOperation[Type: " + operation.getOperationType().toString() + ", PK: " + (operation.getPartitionKeyValue() != null ? operation.getPartitionKeyValue().toString() : "n/a") + ", id: " + operation.getId() + "]"; } private static String getThreadInfo() { StringBuilder sb = new StringBuilder(); Thread t = Thread.currentThread(); sb .append("Thread[") .append("Name: ") .append(t.getName()) .append(",Group: ") .append(t.getThreadGroup() != null ? t.getThreadGroup().getName() : "n/a") .append(", isDaemon: ") .append(t.isDaemon()) .append(", Id: ") .append(t.getId()) .append("]"); return sb.toString(); } private static class SerializedEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } logger.error("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; } } private static class SerializedCompleteEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } if (emitResult == Sinks.EmitResult.FAIL_CANCELLED || emitResult == Sinks.EmitResult.FAIL_TERMINATED) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Main sink already completed, Signal:{}, Result: {}", signalType, emitResult); return false; } logger.error("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; } } }
class BulkExecutor<TContext> implements Disposable { private final static ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper.CosmosBulkExecutionOptionsAccessor bulkOptionsAccessor = ImplementationBridgeHelpers .CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor(); private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private static final ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor clientAccessor = ImplementationBridgeHelpers.CosmosAsyncClientHelper.getCosmosAsyncClientAccessor(); private final CosmosAsyncContainer container; private final int maxMicroBatchPayloadSizeInBytes; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicBoolean isDisposed = new AtomicBoolean(false); private final AtomicBoolean isShutdown = new AtomicBoolean(false); private final AtomicInteger totalCount; private final static Sinks.EmitFailureHandler serializedEmitFailureHandler = new SerializedEmitFailureHandler(); private final static Sinks.EmitFailureHandler serializedCompleteEmitFailureHandler = new SerializedCompleteEmitFailureHandler();; private final Sinks.Many<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final CosmosAsyncClient cosmosClient; private final String bulkSpanName; private final AtomicReference<Disposable> scheduledFutureForFlush; private final String identifier = "BulkExecutor-" + instanceCount.incrementAndGet(); private final BulkExecutorDiagnosticsTracker diagnosticsTracker; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.maxMicroBatchPayloadSizeInBytes = bulkOptionsAccessor .getMaxMicroBatchPayloadSizeInBytes(cosmosBulkOptions); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.bulkSpanName = "nonTransactionalBatch." + this.container.getId(); this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.cosmosClient = ImplementationBridgeHelpers .CosmosAsyncDatabaseHelper .getCosmosAsyncDatabaseAccessor() .getCosmosAsyncClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = bulkOptionsAccessor .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = bulkOptionsAccessor .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = bulkOptionsAccessor .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = identifier + "[" + operationListener.getOperationContext().toString() + "]"; } else { operationContextText = identifier +"[n/a]"; } this.diagnosticsTracker = bulkOptionsAccessor.getDiagnosticsTracker(cosmosBulkOptions); mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainSink = Sinks.many().unicast().onBackpressureBuffer(); groupSinks = new CopyOnWriteArrayList<>(); this.scheduledFutureForFlush = new AtomicReference<>(CosmosSchedulers .BULK_EXECUTOR_FLUSH_BOUNDED_ELASTIC .schedulePeriodically( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS)); logger.debug("Instantiated BulkExecutor, Context: {}", this.operationContextText); } @Override public void dispose() { if (this.isDisposed.compareAndSet(false, true)) { long totalCountSnapshot = totalCount.get(); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.shutdown(); } } } @Override public boolean isDisposed() { return this.isDisposed.get(); } private void cancelFlushTask(boolean initializeAggressiveFlush) { long flushIntervalAfterDrainingIncomingFlux = Math.min( this.maxMicroBatchIntervalInMs, BatchRequestResponseConstants .DEFAULT_MAX_MICRO_BATCH_INTERVAL_AFTER_DRAINING_INCOMING_FLUX_IN_MILLISECONDS); Disposable newFlushTask = initializeAggressiveFlush ? CosmosSchedulers .BULK_EXECUTOR_FLUSH_BOUNDED_ELASTIC .schedulePeriodically( this::onFlush, flushIntervalAfterDrainingIncomingFlux, flushIntervalAfterDrainingIncomingFlux, TimeUnit.MILLISECONDS) : null; Disposable scheduledFutureSnapshot = this.scheduledFutureForFlush.getAndSet(newFlushTask); if (scheduledFutureSnapshot != null) { try { scheduledFutureSnapshot.dispose(); logDebugOrWarning("Cancelled all future scheduled tasks {}, Context: {}", getThreadInfo(), this.operationContextText); } catch (Exception e) { logger.warn("Failed to cancel scheduled tasks{}, Context: {}", getThreadInfo(), this.operationContextText, e); } } } private void logInfoOrWarning(String msg, Object... args) { if (this.diagnosticsTracker == null || !this.diagnosticsTracker.verboseLoggingAfterReEnqueueingRetriesEnabled()) { logger.info(msg, args); } else { logger.warn(msg, args); } } private void logDebugOrWarning(String msg, Object... args) { if (this.diagnosticsTracker == null || !this.diagnosticsTracker.verboseLoggingAfterReEnqueueingRetriesEnabled()) { logger.debug(msg, args); } else { logger.warn(msg, args); } } private void shutdown() { if (this.isShutdown.compareAndSet(false, true)) { logDebugOrWarning("Shutting down, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); this.cancelFlushTask(false); } } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this .executeCore() .doFinally((SignalType signal) -> { if (signal == SignalType.ON_COMPLETE) { logDebugOrWarning("BulkExecutor.execute flux completed - this.totalCount.get(), this.operationContextText, getThreadInfo()); } else { int itemsLeftSnapshot = this.totalCount.get(); if (itemsLeftSnapshot > 0) { logInfoOrWarning("BulkExecutor.execute flux terminated - Signal: {} - signal, itemsLeftSnapshot, this.operationContextText, getThreadInfo()); } else { logDebugOrWarning("BulkExecutor.execute flux terminated - Signal: {} - signal, itemsLeftSnapshot, this.operationContextText, getThreadInfo()); } } this.dispose(); }); } private Flux<CosmosBulkOperationResponse<TContext>> executeCore() { } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); AtomicInteger currentTotalSerializedLength = new AtomicInteger(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); logger.trace( "BufferUntil - enqueued {}, {}, Context: {} {}", timestamp, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (itemOperation == FlushBuffersItemOperation.singleton()) { long currentMicroBatchSizeSnapshot = currentMicroBatchSize.get(); if (currentMicroBatchSizeSnapshot > 0) { logger.trace( "Flushing PKRange {} (batch size: {}) due to FlushItemOperation, Context: {} {}", thresholds.getPartitionKeyRangeId(), currentMicroBatchSizeSnapshot, this.operationContextText, getThreadInfo()); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); currentTotalSerializedLength.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); int totalSerializedLength = this.calculateTotalSerializedLength(currentTotalSerializedLength, itemOperation); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs || totalSerializedLength >= this.maxMicroBatchPayloadSizeInBytes) { logDebugOrWarning( "BufferUntil - Flushing PKRange {} due to BatchSize ({}), payload size ({}) or age ({}), " + "Triggering {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), batchSize, totalSerializedLength, age, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); currentTotalSerializedLength.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } logDebugOrWarning( "Flushing PKRange {} micro batch with {} operations, Context: {} {}", thresholds.getPartitionKeyRangeId(), operations.size(), this.operationContextText, getThreadInfo()); return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private int calculateTotalSerializedLength(AtomicInteger currentTotalSerializedLength, CosmosItemOperation item) { if (item instanceof CosmosItemOperationBase) { return currentTotalSerializedLength.accumulateAndGet( ((CosmosItemOperationBase) item).getSerializedLength(), Integer::sum); } return currentTotalSerializedLength.get(); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.trace("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange, this.maxMicroBatchPayloadSizeInBytes); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .subscribeOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMapMany(response -> { if (diagnosticsTracker != null && response.getDiagnostics() != null) { diagnosticsTracker.trackDiagnostics(response.getDiagnostics().getDiagnosticsContext()); } return Flux .fromIterable(response.getResults()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds)); }) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux .fromIterable(serverRequest.getOperations()) .publishOn(CosmosSchedulers.BULK_EXECUTOR_BOUNDED_ELASTIC) .flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal .createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); logDebugOrWarning( "HandleTransactionalBatchOperationResult - PKRange {}, Response Status Code {}, " + "Operation Status Code, {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { logDebugOrWarning( "HandleTransactionalBatchOperationResult - enqueue retry, PKRange {}, Response " + "Status Code {}, Operation Status Code, {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { if (response.getStatusCode() == HttpConstants.StatusCodes.CONFLICT || response.getStatusCode() == HttpConstants.StatusCodes.PRECONDITION_FAILED) { logDebugOrWarning( "HandleTransactionalBatchOperationResult - Fail, PKRange {}, Response Status " + "Code {}, Operation Status Code {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); } else { logger.error( "HandleTransactionalBatchOperationResult - Fail, PKRange {}, Response Status " + "Code {}, Operation Status Code {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), response.getStatusCode(), operationResult.getStatusCode(), getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); } return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { logDebugOrWarning( "HandleTransactionalBatchExecutionException, PKRange {}, Error: {}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode(), itemBulkOperation, cosmosException) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { logDebugOrWarning( "HandleTransactionalBatchExecutionException - Retry due to split, PKRange {}, Error: " + "{}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); mainSink.emitNext(itemOperation, serializedEmitFailureHandler); return Mono.empty(); } else { logDebugOrWarning( "HandleTransactionalBatchExecutionException - Retry other, PKRange {}, Error: " + "{}, {}, Context: {} {}", thresholds.getPartitionKeyRangeId(), exception, getItemOperationDiagnostics(itemOperation), this.operationContextText, getThreadInfo()); return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setThroughputControlGroupName(cosmosBulkExecutionOptions.getThroughputControlGroupName()); options.setExcludeRegions(cosmosBulkExecutionOptions.getExcludedRegions()); Map<String, String> customOptions = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getCustomOptions(cosmosBulkExecutionOptions); if (customOptions != null && !customOptions.isEmpty()) { for(Map.Entry<String, String> entry : customOptions.entrySet()) { options.setHeader(entry.getKey(), entry.getValue()); } } options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getOperationType() == CosmosItemOperationType.READ || (itemBulkOperation.getRequestOptions() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled())) { options.setContentResponseOnWriteEnabled(true); break; } } } } return withContext(context -> { final Mono<CosmosBatchResponse> responseMono = this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); return clientAccessor.getDiagnosticsProvider(this.cosmosClient) .traceEnabledBatchResponsePublisher( responseMono, context, this.bulkSpanName, this.container.getDatabase().getId(), this.container.getId(), this.cosmosClient, options.getConsistencyLevel(), OperationType.Batch, ResourceType.Document, options); }); } private void completeAllSinks() { logInfoOrWarning("Closing all sinks, Context: {}", this.operationContextText); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.emitComplete(serializedCompleteEmitFailureHandler); this.shutdown(); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed. Context: {}", this.operationContextText, t); } } private static String getItemOperationDiagnostics(CosmosItemOperation operation) { if (operation == FlushBuffersItemOperation.singleton()) { return "ItemOperation[Type: Flush]"; } return "ItemOperation[Type: " + operation.getOperationType().toString() + ", PK: " + (operation.getPartitionKeyValue() != null ? operation.getPartitionKeyValue().toString() : "n/a") + ", id: " + operation.getId() + "]"; } private static String getThreadInfo() { StringBuilder sb = new StringBuilder(); Thread t = Thread.currentThread(); sb .append("Thread[") .append("Name: ") .append(t.getName()) .append(",Group: ") .append(t.getThreadGroup() != null ? t.getThreadGroup().getName() : "n/a") .append(", isDaemon: ") .append(t.isDaemon()) .append(", Id: ") .append(t.getId()) .append("]"); return sb.toString(); } private static class SerializedEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } logger.error("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; } } private static class SerializedCompleteEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } if (emitResult == Sinks.EmitResult.FAIL_CANCELLED || emitResult == Sinks.EmitResult.FAIL_TERMINATED) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Main sink already completed, Signal:{}, Result: {}", signalType, emitResult); return false; } logger.error("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; } } }
No - Cancelled or Terminated is ok - just the "looser" on synchronization
public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } if (emitResult == Sinks.EmitResult.FAIL_CANCELLED || emitResult == Sinks.EmitResult.FAIL_TERMINATED) { logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Main sink already completed, Signal:{}, Result: {}", signalType, emitResult); return false; } logger.error("SerializedCompleteEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; }
logger.debug("SerializedCompleteEmitFailureHandler.onEmitFailure - Main sink already completed, Signal:{}, Result: {}", signalType, emitResult);
public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { logger.debug("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return true; } logger.error("SerializedEmitFailureHandler.onEmitFailure - Signal:{}, Result: {}", signalType, emitResult); return false; }
class SerializedEmitFailureHandler implements Sinks.EmitFailureHandler { @Override }
class SerializedEmitFailureHandler implements Sinks.EmitFailureHandler { @Override }
Should `ExpandableEnum` case use `getValue`
private static String serialize(ObjectSerializer serializer, Object value) { if (value == null) { return null; } if (value instanceof String) { return (String) value; } else if (value.getClass().isPrimitive() || value.getClass().isEnum() || value instanceof Number || value instanceof Boolean || value instanceof Character || value instanceof DateTimeRfc1123 || value instanceof ExpandableEnum) { return String.valueOf(value); } else if (value instanceof OffsetDateTime) { return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_INSTANT); } else { try (OutputStream outputStream = new ByteArrayOutputStream()) { serializer.serializeToStream(outputStream, value); return outputStream.toString(); } catch (IOException e) { throw new RuntimeException(e); } } }
|| value instanceof ExpandableEnum) {
private static String serialize(ObjectSerializer serializer, Object value) { if (value == null) { return null; } if (value instanceof ExpandableEnum) { value = serialize(serializer, ((ExpandableEnum<?>) value).getValue()); } if (value instanceof String) { return (String) value; } else if (value.getClass().isPrimitive() || value.getClass().isEnum() || value instanceof Number || value instanceof Boolean || value instanceof Character || value instanceof DateTimeRfc1123) { return String.valueOf(value); } else if (value instanceof OffsetDateTime) { return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_INSTANT); } else { try (OutputStream outputStream = new ByteArrayOutputStream()) { serializer.serializeToStream(outputStream, value); return outputStream.toString(); } catch (IOException e) { throw new RuntimeException(e); } } }
class && requestOptionsPosition == -1) { requestOptionsPosition = i; }
class && requestOptionsPosition == -1) { requestOptionsPosition = i; }
Enum and ExpandableEnum both could still have the case where they are wrapping `null` and `toString` returns `null` instead of `"null"`.
private static String serialize(ObjectSerializer serializer, Object value) { if (value == null) { return null; } if (value instanceof String) { return (String) value; } else if (value.getClass().isPrimitive() || value.getClass().isEnum() || value instanceof Number || value instanceof Boolean || value instanceof Character || value instanceof DateTimeRfc1123 || value instanceof ExpandableEnum) { return String.valueOf(value); } else if (value instanceof OffsetDateTime) { return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_INSTANT); } else { try (OutputStream outputStream = new ByteArrayOutputStream()) { serializer.serializeToStream(outputStream, value); return outputStream.toString(); } catch (IOException e) { throw new RuntimeException(e); } } }
|| value.getClass().isEnum()
private static String serialize(ObjectSerializer serializer, Object value) { if (value == null) { return null; } if (value instanceof ExpandableEnum) { value = serialize(serializer, ((ExpandableEnum<?>) value).getValue()); } if (value instanceof String) { return (String) value; } else if (value.getClass().isPrimitive() || value.getClass().isEnum() || value instanceof Number || value instanceof Boolean || value instanceof Character || value instanceof DateTimeRfc1123) { return String.valueOf(value); } else if (value instanceof OffsetDateTime) { return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_INSTANT); } else { try (OutputStream outputStream = new ByteArrayOutputStream()) { serializer.serializeToStream(outputStream, value); return outputStream.toString(); } catch (IOException e) { throw new RuntimeException(e); } } }
class && requestOptionsPosition == -1) { requestOptionsPosition = i; }
class && requestOptionsPosition == -1) { requestOptionsPosition = i; }
can also use `checkNotNull` method. Except null, should we also check whether it is empty?
public static PartitionKey fromObjectArray(Object[] values, boolean strict) { if (values == null) { throw new IllegalArgumentException("values can't be null"); } return new PartitionKey(PartitionKeyInternal.fromObjectArray(values, strict)); }
if (values == null) {
public static PartitionKey fromObjectArray(Object[] values, boolean strict) { checkNotNull(values, "Argument 'values' must not be null."); checkNotNull(strict, "Argument 'strict' must not be null."); if (values.length == 0) { throw new NullPointerException("Argument 'values' must not be null."); } return new PartitionKey(PartitionKeyInternal.fromObjectArray(values, strict)); }
class PartitionKeyBuilder { private final List<Object> partitionKeyValues; /** * Constructor. CREATE a new instance of the PartitionKeyBuilder object. */ public PartitionKeyBuilder() { this.partitionKeyValues = new ArrayList<Object>(); } /** * Adds partition value of type string * @param value The value of type string to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(String value) { this.partitionKeyValues.add(value); return this; } /** * Adds partition value of type double * @param value The value of type double to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(double value) { this.partitionKeyValues.add(value); return this; } /** * Adds partition value of type boolean * @param value The value of type boolean to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(boolean value) { this.partitionKeyValues.add(value); return this; } /** * Adds a null partition key value * @return The current PartitionKeyBuilder object * @deprecated Null value should only be used with PartitionKey constructor. */ @Deprecated public PartitionKeyBuilder addNullValue() { this.partitionKeyValues.add(null); return this; } /** * Adds a None Partition Key value to the path. An error will be raised if used with other paths. * @return The current PartitionKeyBuilder object * @deprecated PartitionKey.None value should only be used with PartitionKey constructor. */ @Deprecated public PartitionKeyBuilder addNoneValue() { this.partitionKeyValues.add(PartitionKey.NONE); return this; } /** * Builds a new instance of the type PartitionKey with the specified Partition Key values. * @return PartitionKey object * @throws IllegalStateException when using PartitionKey.None with other values */ public PartitionKey build() { if(this.partitionKeyValues.size() == 0) { throw new IllegalArgumentException("No partition key value has been specified"); } if(this.partitionKeyValues.size() == 1 && PartitionKey.NONE.equals(this.partitionKeyValues.get(0))) { return PartitionKey.NONE; } if(this.partitionKeyValues.size() > 1 && this.partitionKeyValues.contains(PartitionKey.NONE)) { throw new IllegalStateException("PartitionKey.None can't be used with multiple paths"); } PartitionKeyInternal partitionKeyInternal; Object[] valueArray = new Object[this.partitionKeyValues.size()]; for(int i = 0; i < this.partitionKeyValues.size(); i++) { Object val = this.partitionKeyValues.get(i); if(PartitionKey.NONE.equals(val)) { valueArray[i] = Undefined.value(); } else { valueArray[i] = val; } } partitionKeyInternal = PartitionKeyInternal.fromObjectArray(valueArray, true); return new PartitionKey(partitionKeyInternal); } /** * Returns the PartitionKey from an array of objects that is generated by PartitionKeyInternal * @param values The object array of values to construct the PartitionKey with * @param strict The boolean value for if to use strict on object types * @return The PartitionKey */ /** * Returns the PartitionKey extracted from the document by PartitionKeyHelper * @param document The JsonSerializable object to get the PartitionKey value from * @param partitionKeyDefinition The PartitionKeyDefinition to use to extract the PartitionKey value * @return The PartitionKey */ public static PartitionKey extractPartitionKeyFromDocument( Map<String, Object> document, PartitionKeyDefinition partitionKeyDefinition) throws JsonProcessingException { if (document == null) { throw new IllegalArgumentException("document can't be null"); } if (partitionKeyDefinition == null) { throw new IllegalArgumentException("partitionKeyDefinition can't be null"); } ObjectMapper objectMapper = new ObjectMapper(); return PartitionKeyHelper.extractPartitionKeyFromDocument( new JsonSerializable(objectMapper.writeValueAsString(document)), partitionKeyDefinition); } }
class PartitionKeyBuilder { private final List<Object> partitionKeyValues; /** * Constructor. CREATE a new instance of the PartitionKeyBuilder object. */ public PartitionKeyBuilder() { this.partitionKeyValues = new ArrayList<Object>(); } /** * Adds partition value of type string * @param value The value of type string to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(String value) { this.partitionKeyValues.add(value); return this; } /** * Adds partition value of type double * @param value The value of type double to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(double value) { this.partitionKeyValues.add(value); return this; } /** * Adds partition value of type boolean * @param value The value of type boolean to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(boolean value) { this.partitionKeyValues.add(value); return this; } /** * Adds a null partition key value * @return The current PartitionKeyBuilder object * @deprecated Null value should only be used with PartitionKey constructor. */ @Deprecated public PartitionKeyBuilder addNullValue() { this.partitionKeyValues.add(null); return this; } /** * Adds a None Partition Key value to the path. An error will be raised if used with other paths. * @return The current PartitionKeyBuilder object * @deprecated PartitionKey.None value should only be used with PartitionKey constructor. */ @Deprecated public PartitionKeyBuilder addNoneValue() { this.partitionKeyValues.add(PartitionKey.NONE); return this; } /** * Builds a new instance of the type PartitionKey with the specified Partition Key values. * @return PartitionKey object * @throws IllegalStateException when using PartitionKey.None with other values */ public PartitionKey build() { if(this.partitionKeyValues.size() == 0) { throw new IllegalArgumentException("No partition key value has been specified"); } if(this.partitionKeyValues.size() == 1 && PartitionKey.NONE.equals(this.partitionKeyValues.get(0))) { return PartitionKey.NONE; } if(this.partitionKeyValues.size() > 1 && this.partitionKeyValues.contains(PartitionKey.NONE)) { throw new IllegalStateException("PartitionKey.None can't be used with multiple paths"); } PartitionKeyInternal partitionKeyInternal; Object[] valueArray = new Object[this.partitionKeyValues.size()]; for(int i = 0; i < this.partitionKeyValues.size(); i++) { Object val = this.partitionKeyValues.get(i); if(PartitionKey.NONE.equals(val)) { valueArray[i] = Undefined.value(); } else { valueArray[i] = val; } } partitionKeyInternal = PartitionKeyInternal.fromObjectArray(valueArray, true); return new PartitionKey(partitionKeyInternal); } /** * Returns the PartitionKey from an array of objects that is generated by PartitionKeyInternal * @param values The object array of values to construct the PartitionKey with * @param strict The boolean value for if to use strict on object types * @return The PartitionKey */ /** * Returns the PartitionKey extracted from the document by PartitionKeyHelper * @param item The JsonSerializable object to get the PartitionKey value from * @param partitionKeyDefinition The PartitionKeyDefinition to use to extract the PartitionKey value * @return The PartitionKey */ public static PartitionKey extractPartitionKey( Map<String, Object> item, PartitionKeyDefinition partitionKeyDefinition) { checkNotNull(item, "Argument 'item' must not be null."); checkNotNull(partitionKeyDefinition, "Argument 'partitionKeyDefinition' must not be null."); return PartitionKeyHelper.extractPartitionKeyFromDocument( new JsonSerializable(Utils.getSimpleObjectMapper().convertValue(item, ObjectNode.class)), partitionKeyDefinition); } }
Done
public static PartitionKey fromObjectArray(Object[] values, boolean strict) { if (values == null) { throw new IllegalArgumentException("values can't be null"); } return new PartitionKey(PartitionKeyInternal.fromObjectArray(values, strict)); }
if (values == null) {
public static PartitionKey fromObjectArray(Object[] values, boolean strict) { checkNotNull(values, "Argument 'values' must not be null."); checkNotNull(strict, "Argument 'strict' must not be null."); if (values.length == 0) { throw new NullPointerException("Argument 'values' must not be null."); } return new PartitionKey(PartitionKeyInternal.fromObjectArray(values, strict)); }
class PartitionKeyBuilder { private final List<Object> partitionKeyValues; /** * Constructor. CREATE a new instance of the PartitionKeyBuilder object. */ public PartitionKeyBuilder() { this.partitionKeyValues = new ArrayList<Object>(); } /** * Adds partition value of type string * @param value The value of type string to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(String value) { this.partitionKeyValues.add(value); return this; } /** * Adds partition value of type double * @param value The value of type double to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(double value) { this.partitionKeyValues.add(value); return this; } /** * Adds partition value of type boolean * @param value The value of type boolean to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(boolean value) { this.partitionKeyValues.add(value); return this; } /** * Adds a null partition key value * @return The current PartitionKeyBuilder object * @deprecated Null value should only be used with PartitionKey constructor. */ @Deprecated public PartitionKeyBuilder addNullValue() { this.partitionKeyValues.add(null); return this; } /** * Adds a None Partition Key value to the path. An error will be raised if used with other paths. * @return The current PartitionKeyBuilder object * @deprecated PartitionKey.None value should only be used with PartitionKey constructor. */ @Deprecated public PartitionKeyBuilder addNoneValue() { this.partitionKeyValues.add(PartitionKey.NONE); return this; } /** * Builds a new instance of the type PartitionKey with the specified Partition Key values. * @return PartitionKey object * @throws IllegalStateException when using PartitionKey.None with other values */ public PartitionKey build() { if(this.partitionKeyValues.size() == 0) { throw new IllegalArgumentException("No partition key value has been specified"); } if(this.partitionKeyValues.size() == 1 && PartitionKey.NONE.equals(this.partitionKeyValues.get(0))) { return PartitionKey.NONE; } if(this.partitionKeyValues.size() > 1 && this.partitionKeyValues.contains(PartitionKey.NONE)) { throw new IllegalStateException("PartitionKey.None can't be used with multiple paths"); } PartitionKeyInternal partitionKeyInternal; Object[] valueArray = new Object[this.partitionKeyValues.size()]; for(int i = 0; i < this.partitionKeyValues.size(); i++) { Object val = this.partitionKeyValues.get(i); if(PartitionKey.NONE.equals(val)) { valueArray[i] = Undefined.value(); } else { valueArray[i] = val; } } partitionKeyInternal = PartitionKeyInternal.fromObjectArray(valueArray, true); return new PartitionKey(partitionKeyInternal); } /** * Returns the PartitionKey from an array of objects that is generated by PartitionKeyInternal * @param values The object array of values to construct the PartitionKey with * @param strict The boolean value for if to use strict on object types * @return The PartitionKey */ /** * Returns the PartitionKey extracted from the document by PartitionKeyHelper * @param document The JsonSerializable object to get the PartitionKey value from * @param partitionKeyDefinition The PartitionKeyDefinition to use to extract the PartitionKey value * @return The PartitionKey */ public static PartitionKey extractPartitionKeyFromDocument( Map<String, Object> document, PartitionKeyDefinition partitionKeyDefinition) throws JsonProcessingException { if (document == null) { throw new IllegalArgumentException("document can't be null"); } if (partitionKeyDefinition == null) { throw new IllegalArgumentException("partitionKeyDefinition can't be null"); } ObjectMapper objectMapper = new ObjectMapper(); return PartitionKeyHelper.extractPartitionKeyFromDocument( new JsonSerializable(objectMapper.writeValueAsString(document)), partitionKeyDefinition); } }
class PartitionKeyBuilder { private final List<Object> partitionKeyValues; /** * Constructor. CREATE a new instance of the PartitionKeyBuilder object. */ public PartitionKeyBuilder() { this.partitionKeyValues = new ArrayList<Object>(); } /** * Adds partition value of type string * @param value The value of type string to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(String value) { this.partitionKeyValues.add(value); return this; } /** * Adds partition value of type double * @param value The value of type double to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(double value) { this.partitionKeyValues.add(value); return this; } /** * Adds partition value of type boolean * @param value The value of type boolean to be used as partition key * @return The current PartitionKeyBuilder object */ public PartitionKeyBuilder add(boolean value) { this.partitionKeyValues.add(value); return this; } /** * Adds a null partition key value * @return The current PartitionKeyBuilder object * @deprecated Null value should only be used with PartitionKey constructor. */ @Deprecated public PartitionKeyBuilder addNullValue() { this.partitionKeyValues.add(null); return this; } /** * Adds a None Partition Key value to the path. An error will be raised if used with other paths. * @return The current PartitionKeyBuilder object * @deprecated PartitionKey.None value should only be used with PartitionKey constructor. */ @Deprecated public PartitionKeyBuilder addNoneValue() { this.partitionKeyValues.add(PartitionKey.NONE); return this; } /** * Builds a new instance of the type PartitionKey with the specified Partition Key values. * @return PartitionKey object * @throws IllegalStateException when using PartitionKey.None with other values */ public PartitionKey build() { if(this.partitionKeyValues.size() == 0) { throw new IllegalArgumentException("No partition key value has been specified"); } if(this.partitionKeyValues.size() == 1 && PartitionKey.NONE.equals(this.partitionKeyValues.get(0))) { return PartitionKey.NONE; } if(this.partitionKeyValues.size() > 1 && this.partitionKeyValues.contains(PartitionKey.NONE)) { throw new IllegalStateException("PartitionKey.None can't be used with multiple paths"); } PartitionKeyInternal partitionKeyInternal; Object[] valueArray = new Object[this.partitionKeyValues.size()]; for(int i = 0; i < this.partitionKeyValues.size(); i++) { Object val = this.partitionKeyValues.get(i); if(PartitionKey.NONE.equals(val)) { valueArray[i] = Undefined.value(); } else { valueArray[i] = val; } } partitionKeyInternal = PartitionKeyInternal.fromObjectArray(valueArray, true); return new PartitionKey(partitionKeyInternal); } /** * Returns the PartitionKey from an array of objects that is generated by PartitionKeyInternal * @param values The object array of values to construct the PartitionKey with * @param strict The boolean value for if to use strict on object types * @return The PartitionKey */ /** * Returns the PartitionKey extracted from the document by PartitionKeyHelper * @param item The JsonSerializable object to get the PartitionKey value from * @param partitionKeyDefinition The PartitionKeyDefinition to use to extract the PartitionKey value * @return The PartitionKey */ public static PartitionKey extractPartitionKey( Map<String, Object> item, PartitionKeyDefinition partitionKeyDefinition) { checkNotNull(item, "Argument 'item' must not be null."); checkNotNull(partitionKeyDefinition, "Argument 'partitionKeyDefinition' must not be null."); return PartitionKeyHelper.extractPartitionKeyFromDocument( new JsonSerializable(Utils.getSimpleObjectMapper().convertValue(item, ObjectNode.class)), partitionKeyDefinition); } }
Can this throw an error which we are not handling here?
public void put(Collection<SinkRecord> records) { if (records == null || records.isEmpty()) { LOGGER.debug("No records to be written"); return; } LOGGER.debug("Sending {} records to be written", records.size()); Map<String, List<SinkRecord>> recordsByContainer = records.stream().collect( Collectors.groupingBy( record -> this.sinkTaskConfig .getContainersConfig() .getTopicToContainerMap() .getOrDefault(record.topic(), StringUtils.EMPTY))); if (recordsByContainer.containsKey(StringUtils.EMPTY)) { throw new IllegalStateException("There is no container defined for topics " + recordsByContainer.get(StringUtils.EMPTY)); } for (Map.Entry<String, List<SinkRecord>> entry : recordsByContainer.entrySet()) { String containerName = entry.getKey(); CosmosAsyncContainer container = this.cosmosClient .getDatabase(this.sinkTaskConfig.getContainersConfig().getDatabaseName()) .getContainer(containerName); CosmosThroughputControlHelper .tryEnableThroughputControl( container, this.throughputControlClient, this.sinkTaskConfig.getThroughputControlConfig()); List<SinkRecord> transformedRecords = sinkRecordTransformer.transform(containerName, entry.getValue()); this.cosmosWriter.write(container, transformedRecords); } }
.tryEnableThroughputControl(
public void put(Collection<SinkRecord> records) { if (records == null || records.isEmpty()) { LOGGER.debug("No records to be written"); return; } LOGGER.debug("Sending {} records to be written", records.size()); Map<String, List<SinkRecord>> recordsByContainer = records.stream().collect( Collectors.groupingBy( record -> this.sinkTaskConfig .getContainersConfig() .getTopicToContainerMap() .getOrDefault(record.topic(), StringUtils.EMPTY))); if (recordsByContainer.containsKey(StringUtils.EMPTY)) { throw new IllegalStateException("There is no container defined for topics " + recordsByContainer.get(StringUtils.EMPTY)); } for (Map.Entry<String, List<SinkRecord>> entry : recordsByContainer.entrySet()) { String containerName = entry.getKey(); CosmosAsyncContainer container = this.cosmosClient .getDatabase(this.sinkTaskConfig.getContainersConfig().getDatabaseName()) .getContainer(containerName); CosmosThroughputControlHelper .tryEnableThroughputControl( container, this.throughputControlClient, this.sinkTaskConfig.getThroughputControlConfig()); List<SinkRecord> transformedRecords = sinkRecordTransformer.transform(containerName, entry.getValue()); this.cosmosWriter.write(container, transformedRecords); } }
class CosmosSinkTask extends SinkTask { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkTask.class); private CosmosSinkTaskConfig sinkTaskConfig; private CosmosAsyncClient cosmosClient; private CosmosAsyncClient throughputControlClient; private SinkRecordTransformer sinkRecordTransformer; private IWriter cosmosWriter; @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink task"); this.sinkTaskConfig = new CosmosSinkTaskConfig(props); this.cosmosClient = CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getAccountConfig()); this.throughputControlClient = this.getThroughputControlCosmosClient(); this.sinkRecordTransformer = new SinkRecordTransformer(this.sinkTaskConfig); if (this.sinkTaskConfig.getWriteConfig().isBulkEnabled()) { this.cosmosWriter = new KafkaCosmosBulkWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), this.context.errantRecordReporter()); } else { this.cosmosWriter = new KafkaCosmosPointWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), context.errantRecordReporter()); } } private CosmosAsyncClient getThroughputControlCosmosClient() { if (this.sinkTaskConfig.getThroughputControlConfig().isThroughputControlEnabled() && this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig() != null) { return CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig()); } else { return this.cosmosClient; } } @Override @Override public void stop() { LOGGER.info("Stopping Kafka CosmosDB sink task"); if (this.cosmosClient != null) { this.cosmosClient.close(); } } }
class CosmosSinkTask extends SinkTask { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkTask.class); private CosmosSinkTaskConfig sinkTaskConfig; private CosmosAsyncClient cosmosClient; private CosmosAsyncClient throughputControlClient; private SinkRecordTransformer sinkRecordTransformer; private IWriter cosmosWriter; @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink task"); this.sinkTaskConfig = new CosmosSinkTaskConfig(props); this.cosmosClient = CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getAccountConfig()); this.throughputControlClient = this.getThroughputControlCosmosClient(); this.sinkRecordTransformer = new SinkRecordTransformer(this.sinkTaskConfig); if (this.sinkTaskConfig.getWriteConfig().isBulkEnabled()) { this.cosmosWriter = new KafkaCosmosBulkWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), this.context.errantRecordReporter()); } else { this.cosmosWriter = new KafkaCosmosPointWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), context.errantRecordReporter()); } } private CosmosAsyncClient getThroughputControlCosmosClient() { if (this.sinkTaskConfig.getThroughputControlConfig().isThroughputControlEnabled() && this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig() != null) { return CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig()); } else { return this.cosmosClient; } } @Override @Override public void stop() { LOGGER.info("Stopping Kafka CosmosDB sink task"); if (this.cosmosClient != null) { this.cosmosClient.close(); } } }
Same for this one, the methods are in the form of `try....()` which indicates they are going to try to do something, and if they can't what's the behavior we are expecting?
private CosmosBulkExecutionOptions getBulkExecutionOperations() { CosmosBulkExecutionOptions bulkExecutionOptions = new CosmosBulkExecutionOptions(); bulkExecutionOptions.setInitialMicroBatchSize(this.writeConfig.getBulkInitialBatchSize()); if (this.writeConfig.getBulkMaxConcurrentCosmosPartitions() > 0) { ImplementationBridgeHelpers .CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setMaxConcurrentCosmosPartitions(bulkExecutionOptions, this.writeConfig.getBulkMaxConcurrentCosmosPartitions()); } CosmosThroughputControlHelper.tryPopulateThroughputControlGroupName(bulkExecutionOptions, this.throughputControlConfig); return bulkExecutionOptions; }
CosmosThroughputControlHelper.tryPopulateThroughputControlGroupName(bulkExecutionOptions, this.throughputControlConfig);
private CosmosBulkExecutionOptions getBulkExecutionOperations() { CosmosBulkExecutionOptions bulkExecutionOptions = new CosmosBulkExecutionOptions(); bulkExecutionOptions.setInitialMicroBatchSize(this.writeConfig.getBulkInitialBatchSize()); if (this.writeConfig.getBulkMaxConcurrentCosmosPartitions() > 0) { ImplementationBridgeHelpers .CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setMaxConcurrentCosmosPartitions(bulkExecutionOptions, this.writeConfig.getBulkMaxConcurrentCosmosPartitions()); } CosmosThroughputControlHelper.tryPopulateThroughputControlGroupName(bulkExecutionOptions, this.throughputControlConfig); return bulkExecutionOptions; }
class KafkaCosmosBulkWriter extends KafkaCosmosWriterBase { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaCosmosBulkWriter.class); private static final int MAX_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS = 10000; private static final int MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS = 1000; private static final Random RANDOM = new Random(); private final CosmosSinkWriteConfig writeConfig; private final CosmosThroughputControlConfig throughputControlConfig; private final Sinks.EmitFailureHandler emitFailureHandler; public KafkaCosmosBulkWriter( CosmosSinkWriteConfig writeConfig, CosmosThroughputControlConfig throughputControlConfig, ErrantRecordReporter errantRecordReporter) { super(errantRecordReporter); checkNotNull(writeConfig, "Argument 'writeConfig' can not be null"); this.writeConfig = writeConfig; this.throughputControlConfig = throughputControlConfig; this.emitFailureHandler = new KafkaCosmosEmitFailureHandler(); } @Override public void writeCore(CosmosAsyncContainer container, List<SinkOperation> sinkOperations) { Sinks.Many<CosmosItemOperation> bulkRetryEmitter = Sinks.many().unicast().onBackpressureBuffer(); CosmosBulkExecutionOptions bulkExecutionOptions = this.getBulkExecutionOperations(); AtomicInteger totalPendingRecords = new AtomicInteger(sinkOperations.size()); Runnable onTaskCompleteCheck = () -> { if (totalPendingRecords.decrementAndGet() <= 0) { bulkRetryEmitter.emitComplete(emitFailureHandler); } }; Flux.fromIterable(sinkOperations) .flatMap(sinkOperation -> this.getBulkOperation(container, sinkOperation)) .collectList() .flatMapMany(itemOperations -> { Flux<CosmosBulkOperationResponse<Object>> cosmosBulkOperationResponseFlux = container .executeBulkOperations( Flux.fromIterable(itemOperations) .mergeWith(bulkRetryEmitter.asFlux()) .publishOn(KafkaCosmosSchedulers.SINK_BOUNDED_ELASTIC), bulkExecutionOptions); return cosmosBulkOperationResponseFlux; }) .flatMap(itemResponse -> { SinkOperation sinkOperation = itemResponse.getOperation().getContext(); checkNotNull(sinkOperation, "sinkOperation should not be null"); if (itemResponse.getResponse() != null && itemResponse.getResponse().isSuccessStatusCode()) { this.completeSinkOperation(sinkOperation, onTaskCompleteCheck); } else { BulkOperationFailedException exception = handleErrorStatusCode( itemResponse.getResponse(), itemResponse.getException(), sinkOperation); if (shouldIgnore(exception)) { this.completeSinkOperation(sinkOperation, onTaskCompleteCheck); } else { if (shouldRetry(exception, sinkOperation.getRetryCount(), this.writeConfig.getMaxRetryCount())) { sinkOperation.setException(exception); return this.scheduleRetry(container, itemResponse.getOperation().getContext(), bulkRetryEmitter, exception); } else { this.completeSinkOperationWithFailure(sinkOperation, exception, onTaskCompleteCheck); if (this.writeConfig.getToleranceOnErrorLevel() == ToleranceOnErrorLevel.ALL) { LOGGER.warn( "Could not upload record {} to CosmosDB after exhausting all retries, " + "but ToleranceOnErrorLevel is all, will only log the error message. ", sinkOperation.getSinkRecord().key(), sinkOperation.getException()); return Mono.empty(); } else { return Mono.error(exception); } } } } return Mono.empty(); }) .subscribeOn(KafkaCosmosSchedulers.SINK_BOUNDED_ELASTIC) .blockLast(); } private Mono<CosmosItemOperation> getBulkOperation( CosmosAsyncContainer container, SinkOperation sinkOperation) { return ImplementationBridgeHelpers .CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getPartitionKeyDefinition(container) .flatMap(partitionKeyDefinition -> { CosmosItemOperation cosmosItemOperation; switch (this.writeConfig.getItemWriteStrategy()) { case ITEM_OVERWRITE: cosmosItemOperation = this.getUpsertItemOperation(sinkOperation, partitionKeyDefinition); break; case ITEM_OVERWRITE_IF_NOT_MODIFIED: String etag = getEtag(sinkOperation.getSinkRecord().value()); if (StringUtils.isEmpty(etag)) { cosmosItemOperation = this.getCreateItemOperation(sinkOperation, partitionKeyDefinition); } else { cosmosItemOperation = this.getReplaceItemOperation(sinkOperation, partitionKeyDefinition, etag); } break; case ITEM_APPEND: cosmosItemOperation = this.getCreateItemOperation(sinkOperation, partitionKeyDefinition); break; case ITEM_DELETE: cosmosItemOperation = this.getDeleteItemOperation(sinkOperation, partitionKeyDefinition, null); break; case ITEM_DELETE_IF_NOT_MODIFIED: String itemDeleteEtag = getEtag(sinkOperation.getSinkRecord().value()); cosmosItemOperation = this.getDeleteItemOperation(sinkOperation, partitionKeyDefinition, itemDeleteEtag); break; default: return Mono.error(new IllegalArgumentException(this.writeConfig.getItemWriteStrategy() + " is not supported")); } return Mono.just(cosmosItemOperation); }); } private CosmosItemOperation getUpsertItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition) { return CosmosBulkOperations.getUpsertItemOperation( sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), sinkOperation); } private CosmosItemOperation getCreateItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition) { return CosmosBulkOperations.getCreateItemOperation( sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), sinkOperation); } private CosmosItemOperation getReplaceItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition, String etag) { CosmosBulkItemRequestOptions itemRequestOptions = new CosmosBulkItemRequestOptions(); if (StringUtils.isNotEmpty(etag)) { itemRequestOptions.setIfMatchETag(etag); } return CosmosBulkOperations.getReplaceItemOperation( getId(sinkOperation.getSinkRecord().value()), sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), new CosmosBulkItemRequestOptions().setIfMatchETag(etag), sinkOperation); } private CosmosItemOperation getDeleteItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition, String etag) { CosmosBulkItemRequestOptions itemRequestOptions = new CosmosBulkItemRequestOptions(); if (StringUtils.isNotEmpty(etag)) { itemRequestOptions.setIfMatchETag(etag); } return CosmosBulkOperations.getDeleteItemOperation( this.getId(sinkOperation.getSinkRecord().value()), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), itemRequestOptions, sinkOperation); } private Mono<Void> scheduleRetry( CosmosAsyncContainer container, SinkOperation sinkOperation, Sinks.Many<CosmosItemOperation> bulkRetryEmitter, BulkOperationFailedException exception) { sinkOperation.retry(); Mono<Void> retryMono = getBulkOperation(container, sinkOperation) .flatMap(itemOperation -> { bulkRetryEmitter.emitNext(itemOperation, emitFailureHandler); return Mono.empty(); }); if (KafkaCosmosExceptionsHelper.isTimeoutException(exception)) { Duration delayDuration = Duration.ofMillis( MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS + RANDOM.nextInt(MAX_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS - MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS)); return retryMono.delaySubscription(delayDuration); } return retryMono; } BulkOperationFailedException handleErrorStatusCode( CosmosBulkItemResponse itemResponse, Exception exception, SinkOperation sinkOperationContext) { int effectiveStatusCode = itemResponse != null ? itemResponse.getStatusCode() : (exception != null && exception instanceof CosmosException ? ((CosmosException) exception).getStatusCode() : HttpConstants.StatusCodes.REQUEST_TIMEOUT); int effectiveSubStatusCode = itemResponse != null ? itemResponse.getSubStatusCode() : (exception != null && exception instanceof CosmosException ? ((CosmosException) exception).getSubStatusCode() : 0); String errorMessage = String.format( "Request failed with effectiveStatusCode: {%s}, effectiveSubStatusCode: {%s}, kafkaOffset: {%s}, kafkaPartition: {%s}, topic: {%s}", effectiveStatusCode, effectiveSubStatusCode, sinkOperationContext.getKafkaOffset(), sinkOperationContext.getKafkaPartition(), sinkOperationContext.getTopic()); return new BulkOperationFailedException(effectiveStatusCode, effectiveSubStatusCode, errorMessage, exception); } private boolean shouldIgnore(BulkOperationFailedException failedException) { switch (this.writeConfig.getItemWriteStrategy()) { case ITEM_APPEND: return KafkaCosmosExceptionsHelper.isResourceExistsException(failedException); case ITEM_DELETE: return KafkaCosmosExceptionsHelper.isNotFoundException(failedException); case ITEM_DELETE_IF_NOT_MODIFIED: return KafkaCosmosExceptionsHelper.isNotFoundException(failedException) || KafkaCosmosExceptionsHelper.isPreconditionFailedException(failedException); case ITEM_OVERWRITE_IF_NOT_MODIFIED: return KafkaCosmosExceptionsHelper.isResourceExistsException(failedException) || KafkaCosmosExceptionsHelper.isNotFoundException(failedException) || KafkaCosmosExceptionsHelper.isPreconditionFailedException(failedException); default: return false; } } private void completeSinkOperation(SinkOperation sinkOperationContext, Runnable onCompleteRunnable) { sinkOperationContext.complete(); onCompleteRunnable.run(); } public void completeSinkOperationWithFailure( SinkOperation sinkOperationContext, Exception exception, Runnable onCompleteRunnable) { sinkOperationContext.setException(exception); sinkOperationContext.complete(); onCompleteRunnable.run(); this.sendToDlqIfConfigured(sinkOperationContext); } private static class BulkOperationFailedException extends CosmosException { protected BulkOperationFailedException(int statusCode, int subStatusCode, String message, Throwable cause) { super(statusCode, message, null, cause); BridgeInternal.setSubStatusCode(this, subStatusCode); } } private static class KafkaCosmosEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { LOGGER.debug("emitFailureHandler - Signal: {}, Result: {}", signalType, emitResult.toString()); return true; } else { LOGGER.error("emitFailureHandler - Signal: {}, Result: {}", signalType, emitResult.toString()); return false; } } } }
class KafkaCosmosBulkWriter extends KafkaCosmosWriterBase { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaCosmosBulkWriter.class); private static final int MAX_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS = 10000; private static final int MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS = 1000; private static final Random RANDOM = new Random(); private final CosmosSinkWriteConfig writeConfig; private final CosmosThroughputControlConfig throughputControlConfig; private final Sinks.EmitFailureHandler emitFailureHandler; public KafkaCosmosBulkWriter( CosmosSinkWriteConfig writeConfig, CosmosThroughputControlConfig throughputControlConfig, ErrantRecordReporter errantRecordReporter) { super(errantRecordReporter); checkNotNull(writeConfig, "Argument 'writeConfig' can not be null"); this.writeConfig = writeConfig; this.throughputControlConfig = throughputControlConfig; this.emitFailureHandler = new KafkaCosmosEmitFailureHandler(); } @Override public void writeCore(CosmosAsyncContainer container, List<SinkOperation> sinkOperations) { Sinks.Many<CosmosItemOperation> bulkRetryEmitter = Sinks.many().unicast().onBackpressureBuffer(); CosmosBulkExecutionOptions bulkExecutionOptions = this.getBulkExecutionOperations(); AtomicInteger totalPendingRecords = new AtomicInteger(sinkOperations.size()); Runnable onTaskCompleteCheck = () -> { if (totalPendingRecords.decrementAndGet() <= 0) { bulkRetryEmitter.emitComplete(emitFailureHandler); } }; Flux.fromIterable(sinkOperations) .flatMap(sinkOperation -> this.getBulkOperation(container, sinkOperation)) .collectList() .flatMapMany(itemOperations -> { Flux<CosmosBulkOperationResponse<Object>> cosmosBulkOperationResponseFlux = container .executeBulkOperations( Flux.fromIterable(itemOperations) .mergeWith(bulkRetryEmitter.asFlux()) .publishOn(KafkaCosmosSchedulers.SINK_BOUNDED_ELASTIC), bulkExecutionOptions); return cosmosBulkOperationResponseFlux; }) .flatMap(itemResponse -> { SinkOperation sinkOperation = itemResponse.getOperation().getContext(); checkNotNull(sinkOperation, "sinkOperation should not be null"); if (itemResponse.getResponse() != null && itemResponse.getResponse().isSuccessStatusCode()) { this.completeSinkOperation(sinkOperation, onTaskCompleteCheck); } else { BulkOperationFailedException exception = handleErrorStatusCode( itemResponse.getResponse(), itemResponse.getException(), sinkOperation); if (shouldIgnore(exception)) { this.completeSinkOperation(sinkOperation, onTaskCompleteCheck); } else { if (shouldRetry(exception, sinkOperation.getRetryCount(), this.writeConfig.getMaxRetryCount())) { sinkOperation.setException(exception); return this.scheduleRetry(container, itemResponse.getOperation().getContext(), bulkRetryEmitter, exception); } else { this.completeSinkOperationWithFailure(sinkOperation, exception, onTaskCompleteCheck); if (this.writeConfig.getToleranceOnErrorLevel() == ToleranceOnErrorLevel.ALL) { LOGGER.warn( "Could not upload record {} to CosmosDB after exhausting all retries, " + "but ToleranceOnErrorLevel is all, will only log the error message. ", sinkOperation.getSinkRecord().key(), sinkOperation.getException()); return Mono.empty(); } else { return Mono.error(exception); } } } } return Mono.empty(); }) .subscribeOn(KafkaCosmosSchedulers.SINK_BOUNDED_ELASTIC) .blockLast(); } private Mono<CosmosItemOperation> getBulkOperation( CosmosAsyncContainer container, SinkOperation sinkOperation) { return ImplementationBridgeHelpers .CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getPartitionKeyDefinition(container) .flatMap(partitionKeyDefinition -> { CosmosItemOperation cosmosItemOperation; switch (this.writeConfig.getItemWriteStrategy()) { case ITEM_OVERWRITE: cosmosItemOperation = this.getUpsertItemOperation(sinkOperation, partitionKeyDefinition); break; case ITEM_OVERWRITE_IF_NOT_MODIFIED: String etag = getEtag(sinkOperation.getSinkRecord().value()); if (StringUtils.isEmpty(etag)) { cosmosItemOperation = this.getCreateItemOperation(sinkOperation, partitionKeyDefinition); } else { cosmosItemOperation = this.getReplaceItemOperation(sinkOperation, partitionKeyDefinition, etag); } break; case ITEM_APPEND: cosmosItemOperation = this.getCreateItemOperation(sinkOperation, partitionKeyDefinition); break; case ITEM_DELETE: cosmosItemOperation = this.getDeleteItemOperation(sinkOperation, partitionKeyDefinition, null); break; case ITEM_DELETE_IF_NOT_MODIFIED: String itemDeleteEtag = getEtag(sinkOperation.getSinkRecord().value()); cosmosItemOperation = this.getDeleteItemOperation(sinkOperation, partitionKeyDefinition, itemDeleteEtag); break; default: return Mono.error(new IllegalArgumentException(this.writeConfig.getItemWriteStrategy() + " is not supported")); } return Mono.just(cosmosItemOperation); }); } private CosmosItemOperation getUpsertItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition) { return CosmosBulkOperations.getUpsertItemOperation( sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), sinkOperation); } private CosmosItemOperation getCreateItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition) { return CosmosBulkOperations.getCreateItemOperation( sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), sinkOperation); } private CosmosItemOperation getReplaceItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition, String etag) { CosmosBulkItemRequestOptions itemRequestOptions = new CosmosBulkItemRequestOptions(); if (StringUtils.isNotEmpty(etag)) { itemRequestOptions.setIfMatchETag(etag); } return CosmosBulkOperations.getReplaceItemOperation( getId(sinkOperation.getSinkRecord().value()), sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), new CosmosBulkItemRequestOptions().setIfMatchETag(etag), sinkOperation); } private CosmosItemOperation getDeleteItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition, String etag) { CosmosBulkItemRequestOptions itemRequestOptions = new CosmosBulkItemRequestOptions(); if (StringUtils.isNotEmpty(etag)) { itemRequestOptions.setIfMatchETag(etag); } return CosmosBulkOperations.getDeleteItemOperation( this.getId(sinkOperation.getSinkRecord().value()), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), itemRequestOptions, sinkOperation); } private Mono<Void> scheduleRetry( CosmosAsyncContainer container, SinkOperation sinkOperation, Sinks.Many<CosmosItemOperation> bulkRetryEmitter, BulkOperationFailedException exception) { sinkOperation.retry(); Mono<Void> retryMono = getBulkOperation(container, sinkOperation) .flatMap(itemOperation -> { bulkRetryEmitter.emitNext(itemOperation, emitFailureHandler); return Mono.empty(); }); if (KafkaCosmosExceptionsHelper.isTimeoutException(exception)) { Duration delayDuration = Duration.ofMillis( MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS + RANDOM.nextInt(MAX_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS - MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS)); return retryMono.delaySubscription(delayDuration); } return retryMono; } BulkOperationFailedException handleErrorStatusCode( CosmosBulkItemResponse itemResponse, Exception exception, SinkOperation sinkOperationContext) { int effectiveStatusCode = itemResponse != null ? itemResponse.getStatusCode() : (exception != null && exception instanceof CosmosException ? ((CosmosException) exception).getStatusCode() : HttpConstants.StatusCodes.REQUEST_TIMEOUT); int effectiveSubStatusCode = itemResponse != null ? itemResponse.getSubStatusCode() : (exception != null && exception instanceof CosmosException ? ((CosmosException) exception).getSubStatusCode() : 0); String errorMessage = String.format( "Request failed with effectiveStatusCode: {%s}, effectiveSubStatusCode: {%s}, kafkaOffset: {%s}, kafkaPartition: {%s}, topic: {%s}", effectiveStatusCode, effectiveSubStatusCode, sinkOperationContext.getKafkaOffset(), sinkOperationContext.getKafkaPartition(), sinkOperationContext.getTopic()); return new BulkOperationFailedException(effectiveStatusCode, effectiveSubStatusCode, errorMessage, exception); } private boolean shouldIgnore(BulkOperationFailedException failedException) { switch (this.writeConfig.getItemWriteStrategy()) { case ITEM_APPEND: return KafkaCosmosExceptionsHelper.isResourceExistsException(failedException); case ITEM_DELETE: return KafkaCosmosExceptionsHelper.isNotFoundException(failedException); case ITEM_DELETE_IF_NOT_MODIFIED: return KafkaCosmosExceptionsHelper.isNotFoundException(failedException) || KafkaCosmosExceptionsHelper.isPreconditionFailedException(failedException); case ITEM_OVERWRITE_IF_NOT_MODIFIED: return KafkaCosmosExceptionsHelper.isResourceExistsException(failedException) || KafkaCosmosExceptionsHelper.isNotFoundException(failedException) || KafkaCosmosExceptionsHelper.isPreconditionFailedException(failedException); default: return false; } } private void completeSinkOperation(SinkOperation sinkOperationContext, Runnable onCompleteRunnable) { sinkOperationContext.complete(); onCompleteRunnable.run(); } public void completeSinkOperationWithFailure( SinkOperation sinkOperationContext, Exception exception, Runnable onCompleteRunnable) { sinkOperationContext.setException(exception); sinkOperationContext.complete(); onCompleteRunnable.run(); this.sendToDlqIfConfigured(sinkOperationContext); } private static class BulkOperationFailedException extends CosmosException { protected BulkOperationFailedException(int statusCode, int subStatusCode, String message, Throwable cause) { super(statusCode, message, null, cause); BridgeInternal.setSubStatusCode(this, subStatusCode); } } private static class KafkaCosmosEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { LOGGER.debug("emitFailureHandler - Signal: {}, Result: {}", signalType, emitResult.toString()); return true; } else { LOGGER.error("emitFailureHandler - Signal: {}, Result: {}", signalType, emitResult.toString()); return false; } } } }
hmm, the tryxxx here is based on whether throughput control is enabled -> if it is enabled, then will apply. If not, then skip
private CosmosBulkExecutionOptions getBulkExecutionOperations() { CosmosBulkExecutionOptions bulkExecutionOptions = new CosmosBulkExecutionOptions(); bulkExecutionOptions.setInitialMicroBatchSize(this.writeConfig.getBulkInitialBatchSize()); if (this.writeConfig.getBulkMaxConcurrentCosmosPartitions() > 0) { ImplementationBridgeHelpers .CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setMaxConcurrentCosmosPartitions(bulkExecutionOptions, this.writeConfig.getBulkMaxConcurrentCosmosPartitions()); } CosmosThroughputControlHelper.tryPopulateThroughputControlGroupName(bulkExecutionOptions, this.throughputControlConfig); return bulkExecutionOptions; }
CosmosThroughputControlHelper.tryPopulateThroughputControlGroupName(bulkExecutionOptions, this.throughputControlConfig);
private CosmosBulkExecutionOptions getBulkExecutionOperations() { CosmosBulkExecutionOptions bulkExecutionOptions = new CosmosBulkExecutionOptions(); bulkExecutionOptions.setInitialMicroBatchSize(this.writeConfig.getBulkInitialBatchSize()); if (this.writeConfig.getBulkMaxConcurrentCosmosPartitions() > 0) { ImplementationBridgeHelpers .CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .setMaxConcurrentCosmosPartitions(bulkExecutionOptions, this.writeConfig.getBulkMaxConcurrentCosmosPartitions()); } CosmosThroughputControlHelper.tryPopulateThroughputControlGroupName(bulkExecutionOptions, this.throughputControlConfig); return bulkExecutionOptions; }
class KafkaCosmosBulkWriter extends KafkaCosmosWriterBase { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaCosmosBulkWriter.class); private static final int MAX_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS = 10000; private static final int MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS = 1000; private static final Random RANDOM = new Random(); private final CosmosSinkWriteConfig writeConfig; private final CosmosThroughputControlConfig throughputControlConfig; private final Sinks.EmitFailureHandler emitFailureHandler; public KafkaCosmosBulkWriter( CosmosSinkWriteConfig writeConfig, CosmosThroughputControlConfig throughputControlConfig, ErrantRecordReporter errantRecordReporter) { super(errantRecordReporter); checkNotNull(writeConfig, "Argument 'writeConfig' can not be null"); this.writeConfig = writeConfig; this.throughputControlConfig = throughputControlConfig; this.emitFailureHandler = new KafkaCosmosEmitFailureHandler(); } @Override public void writeCore(CosmosAsyncContainer container, List<SinkOperation> sinkOperations) { Sinks.Many<CosmosItemOperation> bulkRetryEmitter = Sinks.many().unicast().onBackpressureBuffer(); CosmosBulkExecutionOptions bulkExecutionOptions = this.getBulkExecutionOperations(); AtomicInteger totalPendingRecords = new AtomicInteger(sinkOperations.size()); Runnable onTaskCompleteCheck = () -> { if (totalPendingRecords.decrementAndGet() <= 0) { bulkRetryEmitter.emitComplete(emitFailureHandler); } }; Flux.fromIterable(sinkOperations) .flatMap(sinkOperation -> this.getBulkOperation(container, sinkOperation)) .collectList() .flatMapMany(itemOperations -> { Flux<CosmosBulkOperationResponse<Object>> cosmosBulkOperationResponseFlux = container .executeBulkOperations( Flux.fromIterable(itemOperations) .mergeWith(bulkRetryEmitter.asFlux()) .publishOn(KafkaCosmosSchedulers.SINK_BOUNDED_ELASTIC), bulkExecutionOptions); return cosmosBulkOperationResponseFlux; }) .flatMap(itemResponse -> { SinkOperation sinkOperation = itemResponse.getOperation().getContext(); checkNotNull(sinkOperation, "sinkOperation should not be null"); if (itemResponse.getResponse() != null && itemResponse.getResponse().isSuccessStatusCode()) { this.completeSinkOperation(sinkOperation, onTaskCompleteCheck); } else { BulkOperationFailedException exception = handleErrorStatusCode( itemResponse.getResponse(), itemResponse.getException(), sinkOperation); if (shouldIgnore(exception)) { this.completeSinkOperation(sinkOperation, onTaskCompleteCheck); } else { if (shouldRetry(exception, sinkOperation.getRetryCount(), this.writeConfig.getMaxRetryCount())) { sinkOperation.setException(exception); return this.scheduleRetry(container, itemResponse.getOperation().getContext(), bulkRetryEmitter, exception); } else { this.completeSinkOperationWithFailure(sinkOperation, exception, onTaskCompleteCheck); if (this.writeConfig.getToleranceOnErrorLevel() == ToleranceOnErrorLevel.ALL) { LOGGER.warn( "Could not upload record {} to CosmosDB after exhausting all retries, " + "but ToleranceOnErrorLevel is all, will only log the error message. ", sinkOperation.getSinkRecord().key(), sinkOperation.getException()); return Mono.empty(); } else { return Mono.error(exception); } } } } return Mono.empty(); }) .subscribeOn(KafkaCosmosSchedulers.SINK_BOUNDED_ELASTIC) .blockLast(); } private Mono<CosmosItemOperation> getBulkOperation( CosmosAsyncContainer container, SinkOperation sinkOperation) { return ImplementationBridgeHelpers .CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getPartitionKeyDefinition(container) .flatMap(partitionKeyDefinition -> { CosmosItemOperation cosmosItemOperation; switch (this.writeConfig.getItemWriteStrategy()) { case ITEM_OVERWRITE: cosmosItemOperation = this.getUpsertItemOperation(sinkOperation, partitionKeyDefinition); break; case ITEM_OVERWRITE_IF_NOT_MODIFIED: String etag = getEtag(sinkOperation.getSinkRecord().value()); if (StringUtils.isEmpty(etag)) { cosmosItemOperation = this.getCreateItemOperation(sinkOperation, partitionKeyDefinition); } else { cosmosItemOperation = this.getReplaceItemOperation(sinkOperation, partitionKeyDefinition, etag); } break; case ITEM_APPEND: cosmosItemOperation = this.getCreateItemOperation(sinkOperation, partitionKeyDefinition); break; case ITEM_DELETE: cosmosItemOperation = this.getDeleteItemOperation(sinkOperation, partitionKeyDefinition, null); break; case ITEM_DELETE_IF_NOT_MODIFIED: String itemDeleteEtag = getEtag(sinkOperation.getSinkRecord().value()); cosmosItemOperation = this.getDeleteItemOperation(sinkOperation, partitionKeyDefinition, itemDeleteEtag); break; default: return Mono.error(new IllegalArgumentException(this.writeConfig.getItemWriteStrategy() + " is not supported")); } return Mono.just(cosmosItemOperation); }); } private CosmosItemOperation getUpsertItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition) { return CosmosBulkOperations.getUpsertItemOperation( sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), sinkOperation); } private CosmosItemOperation getCreateItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition) { return CosmosBulkOperations.getCreateItemOperation( sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), sinkOperation); } private CosmosItemOperation getReplaceItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition, String etag) { CosmosBulkItemRequestOptions itemRequestOptions = new CosmosBulkItemRequestOptions(); if (StringUtils.isNotEmpty(etag)) { itemRequestOptions.setIfMatchETag(etag); } return CosmosBulkOperations.getReplaceItemOperation( getId(sinkOperation.getSinkRecord().value()), sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), new CosmosBulkItemRequestOptions().setIfMatchETag(etag), sinkOperation); } private CosmosItemOperation getDeleteItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition, String etag) { CosmosBulkItemRequestOptions itemRequestOptions = new CosmosBulkItemRequestOptions(); if (StringUtils.isNotEmpty(etag)) { itemRequestOptions.setIfMatchETag(etag); } return CosmosBulkOperations.getDeleteItemOperation( this.getId(sinkOperation.getSinkRecord().value()), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), itemRequestOptions, sinkOperation); } private Mono<Void> scheduleRetry( CosmosAsyncContainer container, SinkOperation sinkOperation, Sinks.Many<CosmosItemOperation> bulkRetryEmitter, BulkOperationFailedException exception) { sinkOperation.retry(); Mono<Void> retryMono = getBulkOperation(container, sinkOperation) .flatMap(itemOperation -> { bulkRetryEmitter.emitNext(itemOperation, emitFailureHandler); return Mono.empty(); }); if (KafkaCosmosExceptionsHelper.isTimeoutException(exception)) { Duration delayDuration = Duration.ofMillis( MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS + RANDOM.nextInt(MAX_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS - MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS)); return retryMono.delaySubscription(delayDuration); } return retryMono; } BulkOperationFailedException handleErrorStatusCode( CosmosBulkItemResponse itemResponse, Exception exception, SinkOperation sinkOperationContext) { int effectiveStatusCode = itemResponse != null ? itemResponse.getStatusCode() : (exception != null && exception instanceof CosmosException ? ((CosmosException) exception).getStatusCode() : HttpConstants.StatusCodes.REQUEST_TIMEOUT); int effectiveSubStatusCode = itemResponse != null ? itemResponse.getSubStatusCode() : (exception != null && exception instanceof CosmosException ? ((CosmosException) exception).getSubStatusCode() : 0); String errorMessage = String.format( "Request failed with effectiveStatusCode: {%s}, effectiveSubStatusCode: {%s}, kafkaOffset: {%s}, kafkaPartition: {%s}, topic: {%s}", effectiveStatusCode, effectiveSubStatusCode, sinkOperationContext.getKafkaOffset(), sinkOperationContext.getKafkaPartition(), sinkOperationContext.getTopic()); return new BulkOperationFailedException(effectiveStatusCode, effectiveSubStatusCode, errorMessage, exception); } private boolean shouldIgnore(BulkOperationFailedException failedException) { switch (this.writeConfig.getItemWriteStrategy()) { case ITEM_APPEND: return KafkaCosmosExceptionsHelper.isResourceExistsException(failedException); case ITEM_DELETE: return KafkaCosmosExceptionsHelper.isNotFoundException(failedException); case ITEM_DELETE_IF_NOT_MODIFIED: return KafkaCosmosExceptionsHelper.isNotFoundException(failedException) || KafkaCosmosExceptionsHelper.isPreconditionFailedException(failedException); case ITEM_OVERWRITE_IF_NOT_MODIFIED: return KafkaCosmosExceptionsHelper.isResourceExistsException(failedException) || KafkaCosmosExceptionsHelper.isNotFoundException(failedException) || KafkaCosmosExceptionsHelper.isPreconditionFailedException(failedException); default: return false; } } private void completeSinkOperation(SinkOperation sinkOperationContext, Runnable onCompleteRunnable) { sinkOperationContext.complete(); onCompleteRunnable.run(); } public void completeSinkOperationWithFailure( SinkOperation sinkOperationContext, Exception exception, Runnable onCompleteRunnable) { sinkOperationContext.setException(exception); sinkOperationContext.complete(); onCompleteRunnable.run(); this.sendToDlqIfConfigured(sinkOperationContext); } private static class BulkOperationFailedException extends CosmosException { protected BulkOperationFailedException(int statusCode, int subStatusCode, String message, Throwable cause) { super(statusCode, message, null, cause); BridgeInternal.setSubStatusCode(this, subStatusCode); } } private static class KafkaCosmosEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { LOGGER.debug("emitFailureHandler - Signal: {}, Result: {}", signalType, emitResult.toString()); return true; } else { LOGGER.error("emitFailureHandler - Signal: {}, Result: {}", signalType, emitResult.toString()); return false; } } } }
class KafkaCosmosBulkWriter extends KafkaCosmosWriterBase { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaCosmosBulkWriter.class); private static final int MAX_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS = 10000; private static final int MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS = 1000; private static final Random RANDOM = new Random(); private final CosmosSinkWriteConfig writeConfig; private final CosmosThroughputControlConfig throughputControlConfig; private final Sinks.EmitFailureHandler emitFailureHandler; public KafkaCosmosBulkWriter( CosmosSinkWriteConfig writeConfig, CosmosThroughputControlConfig throughputControlConfig, ErrantRecordReporter errantRecordReporter) { super(errantRecordReporter); checkNotNull(writeConfig, "Argument 'writeConfig' can not be null"); this.writeConfig = writeConfig; this.throughputControlConfig = throughputControlConfig; this.emitFailureHandler = new KafkaCosmosEmitFailureHandler(); } @Override public void writeCore(CosmosAsyncContainer container, List<SinkOperation> sinkOperations) { Sinks.Many<CosmosItemOperation> bulkRetryEmitter = Sinks.many().unicast().onBackpressureBuffer(); CosmosBulkExecutionOptions bulkExecutionOptions = this.getBulkExecutionOperations(); AtomicInteger totalPendingRecords = new AtomicInteger(sinkOperations.size()); Runnable onTaskCompleteCheck = () -> { if (totalPendingRecords.decrementAndGet() <= 0) { bulkRetryEmitter.emitComplete(emitFailureHandler); } }; Flux.fromIterable(sinkOperations) .flatMap(sinkOperation -> this.getBulkOperation(container, sinkOperation)) .collectList() .flatMapMany(itemOperations -> { Flux<CosmosBulkOperationResponse<Object>> cosmosBulkOperationResponseFlux = container .executeBulkOperations( Flux.fromIterable(itemOperations) .mergeWith(bulkRetryEmitter.asFlux()) .publishOn(KafkaCosmosSchedulers.SINK_BOUNDED_ELASTIC), bulkExecutionOptions); return cosmosBulkOperationResponseFlux; }) .flatMap(itemResponse -> { SinkOperation sinkOperation = itemResponse.getOperation().getContext(); checkNotNull(sinkOperation, "sinkOperation should not be null"); if (itemResponse.getResponse() != null && itemResponse.getResponse().isSuccessStatusCode()) { this.completeSinkOperation(sinkOperation, onTaskCompleteCheck); } else { BulkOperationFailedException exception = handleErrorStatusCode( itemResponse.getResponse(), itemResponse.getException(), sinkOperation); if (shouldIgnore(exception)) { this.completeSinkOperation(sinkOperation, onTaskCompleteCheck); } else { if (shouldRetry(exception, sinkOperation.getRetryCount(), this.writeConfig.getMaxRetryCount())) { sinkOperation.setException(exception); return this.scheduleRetry(container, itemResponse.getOperation().getContext(), bulkRetryEmitter, exception); } else { this.completeSinkOperationWithFailure(sinkOperation, exception, onTaskCompleteCheck); if (this.writeConfig.getToleranceOnErrorLevel() == ToleranceOnErrorLevel.ALL) { LOGGER.warn( "Could not upload record {} to CosmosDB after exhausting all retries, " + "but ToleranceOnErrorLevel is all, will only log the error message. ", sinkOperation.getSinkRecord().key(), sinkOperation.getException()); return Mono.empty(); } else { return Mono.error(exception); } } } } return Mono.empty(); }) .subscribeOn(KafkaCosmosSchedulers.SINK_BOUNDED_ELASTIC) .blockLast(); } private Mono<CosmosItemOperation> getBulkOperation( CosmosAsyncContainer container, SinkOperation sinkOperation) { return ImplementationBridgeHelpers .CosmosAsyncContainerHelper .getCosmosAsyncContainerAccessor() .getPartitionKeyDefinition(container) .flatMap(partitionKeyDefinition -> { CosmosItemOperation cosmosItemOperation; switch (this.writeConfig.getItemWriteStrategy()) { case ITEM_OVERWRITE: cosmosItemOperation = this.getUpsertItemOperation(sinkOperation, partitionKeyDefinition); break; case ITEM_OVERWRITE_IF_NOT_MODIFIED: String etag = getEtag(sinkOperation.getSinkRecord().value()); if (StringUtils.isEmpty(etag)) { cosmosItemOperation = this.getCreateItemOperation(sinkOperation, partitionKeyDefinition); } else { cosmosItemOperation = this.getReplaceItemOperation(sinkOperation, partitionKeyDefinition, etag); } break; case ITEM_APPEND: cosmosItemOperation = this.getCreateItemOperation(sinkOperation, partitionKeyDefinition); break; case ITEM_DELETE: cosmosItemOperation = this.getDeleteItemOperation(sinkOperation, partitionKeyDefinition, null); break; case ITEM_DELETE_IF_NOT_MODIFIED: String itemDeleteEtag = getEtag(sinkOperation.getSinkRecord().value()); cosmosItemOperation = this.getDeleteItemOperation(sinkOperation, partitionKeyDefinition, itemDeleteEtag); break; default: return Mono.error(new IllegalArgumentException(this.writeConfig.getItemWriteStrategy() + " is not supported")); } return Mono.just(cosmosItemOperation); }); } private CosmosItemOperation getUpsertItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition) { return CosmosBulkOperations.getUpsertItemOperation( sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), sinkOperation); } private CosmosItemOperation getCreateItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition) { return CosmosBulkOperations.getCreateItemOperation( sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), sinkOperation); } private CosmosItemOperation getReplaceItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition, String etag) { CosmosBulkItemRequestOptions itemRequestOptions = new CosmosBulkItemRequestOptions(); if (StringUtils.isNotEmpty(etag)) { itemRequestOptions.setIfMatchETag(etag); } return CosmosBulkOperations.getReplaceItemOperation( getId(sinkOperation.getSinkRecord().value()), sinkOperation.getSinkRecord().value(), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), new CosmosBulkItemRequestOptions().setIfMatchETag(etag), sinkOperation); } private CosmosItemOperation getDeleteItemOperation( SinkOperation sinkOperation, PartitionKeyDefinition partitionKeyDefinition, String etag) { CosmosBulkItemRequestOptions itemRequestOptions = new CosmosBulkItemRequestOptions(); if (StringUtils.isNotEmpty(etag)) { itemRequestOptions.setIfMatchETag(etag); } return CosmosBulkOperations.getDeleteItemOperation( this.getId(sinkOperation.getSinkRecord().value()), this.getPartitionKeyValue(sinkOperation.getSinkRecord().value(), partitionKeyDefinition), itemRequestOptions, sinkOperation); } private Mono<Void> scheduleRetry( CosmosAsyncContainer container, SinkOperation sinkOperation, Sinks.Many<CosmosItemOperation> bulkRetryEmitter, BulkOperationFailedException exception) { sinkOperation.retry(); Mono<Void> retryMono = getBulkOperation(container, sinkOperation) .flatMap(itemOperation -> { bulkRetryEmitter.emitNext(itemOperation, emitFailureHandler); return Mono.empty(); }); if (KafkaCosmosExceptionsHelper.isTimeoutException(exception)) { Duration delayDuration = Duration.ofMillis( MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS + RANDOM.nextInt(MAX_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS - MIN_DELAY_ON_408_REQUEST_TIMEOUT_IN_MS)); return retryMono.delaySubscription(delayDuration); } return retryMono; } BulkOperationFailedException handleErrorStatusCode( CosmosBulkItemResponse itemResponse, Exception exception, SinkOperation sinkOperationContext) { int effectiveStatusCode = itemResponse != null ? itemResponse.getStatusCode() : (exception != null && exception instanceof CosmosException ? ((CosmosException) exception).getStatusCode() : HttpConstants.StatusCodes.REQUEST_TIMEOUT); int effectiveSubStatusCode = itemResponse != null ? itemResponse.getSubStatusCode() : (exception != null && exception instanceof CosmosException ? ((CosmosException) exception).getSubStatusCode() : 0); String errorMessage = String.format( "Request failed with effectiveStatusCode: {%s}, effectiveSubStatusCode: {%s}, kafkaOffset: {%s}, kafkaPartition: {%s}, topic: {%s}", effectiveStatusCode, effectiveSubStatusCode, sinkOperationContext.getKafkaOffset(), sinkOperationContext.getKafkaPartition(), sinkOperationContext.getTopic()); return new BulkOperationFailedException(effectiveStatusCode, effectiveSubStatusCode, errorMessage, exception); } private boolean shouldIgnore(BulkOperationFailedException failedException) { switch (this.writeConfig.getItemWriteStrategy()) { case ITEM_APPEND: return KafkaCosmosExceptionsHelper.isResourceExistsException(failedException); case ITEM_DELETE: return KafkaCosmosExceptionsHelper.isNotFoundException(failedException); case ITEM_DELETE_IF_NOT_MODIFIED: return KafkaCosmosExceptionsHelper.isNotFoundException(failedException) || KafkaCosmosExceptionsHelper.isPreconditionFailedException(failedException); case ITEM_OVERWRITE_IF_NOT_MODIFIED: return KafkaCosmosExceptionsHelper.isResourceExistsException(failedException) || KafkaCosmosExceptionsHelper.isNotFoundException(failedException) || KafkaCosmosExceptionsHelper.isPreconditionFailedException(failedException); default: return false; } } private void completeSinkOperation(SinkOperation sinkOperationContext, Runnable onCompleteRunnable) { sinkOperationContext.complete(); onCompleteRunnable.run(); } public void completeSinkOperationWithFailure( SinkOperation sinkOperationContext, Exception exception, Runnable onCompleteRunnable) { sinkOperationContext.setException(exception); sinkOperationContext.complete(); onCompleteRunnable.run(); this.sendToDlqIfConfigured(sinkOperationContext); } private static class BulkOperationFailedException extends CosmosException { protected BulkOperationFailedException(int statusCode, int subStatusCode, String message, Throwable cause) { super(statusCode, message, null, cause); BridgeInternal.setSubStatusCode(this, subStatusCode); } } private static class KafkaCosmosEmitFailureHandler implements Sinks.EmitFailureHandler { @Override public boolean onEmitFailure(SignalType signalType, Sinks.EmitResult emitResult) { if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { LOGGER.debug("emitFailureHandler - Signal: {}, Result: {}", signalType, emitResult.toString()); return true; } else { LOGGER.error("emitFailureHandler - Signal: {}, Result: {}", signalType, emitResult.toString()); return false; } } } }
very rarely, but possible. I think it will be decided whether we want to suppress any throughput control exception. In azure-cosmos, we allow customer to config continueOnInitError in throughput control config to control the behavior. For Kafka, I think we can start with the default (fail at error), and then if needed, in future add another config to support this extra behavior.
public void put(Collection<SinkRecord> records) { if (records == null || records.isEmpty()) { LOGGER.debug("No records to be written"); return; } LOGGER.debug("Sending {} records to be written", records.size()); Map<String, List<SinkRecord>> recordsByContainer = records.stream().collect( Collectors.groupingBy( record -> this.sinkTaskConfig .getContainersConfig() .getTopicToContainerMap() .getOrDefault(record.topic(), StringUtils.EMPTY))); if (recordsByContainer.containsKey(StringUtils.EMPTY)) { throw new IllegalStateException("There is no container defined for topics " + recordsByContainer.get(StringUtils.EMPTY)); } for (Map.Entry<String, List<SinkRecord>> entry : recordsByContainer.entrySet()) { String containerName = entry.getKey(); CosmosAsyncContainer container = this.cosmosClient .getDatabase(this.sinkTaskConfig.getContainersConfig().getDatabaseName()) .getContainer(containerName); CosmosThroughputControlHelper .tryEnableThroughputControl( container, this.throughputControlClient, this.sinkTaskConfig.getThroughputControlConfig()); List<SinkRecord> transformedRecords = sinkRecordTransformer.transform(containerName, entry.getValue()); this.cosmosWriter.write(container, transformedRecords); } }
.tryEnableThroughputControl(
public void put(Collection<SinkRecord> records) { if (records == null || records.isEmpty()) { LOGGER.debug("No records to be written"); return; } LOGGER.debug("Sending {} records to be written", records.size()); Map<String, List<SinkRecord>> recordsByContainer = records.stream().collect( Collectors.groupingBy( record -> this.sinkTaskConfig .getContainersConfig() .getTopicToContainerMap() .getOrDefault(record.topic(), StringUtils.EMPTY))); if (recordsByContainer.containsKey(StringUtils.EMPTY)) { throw new IllegalStateException("There is no container defined for topics " + recordsByContainer.get(StringUtils.EMPTY)); } for (Map.Entry<String, List<SinkRecord>> entry : recordsByContainer.entrySet()) { String containerName = entry.getKey(); CosmosAsyncContainer container = this.cosmosClient .getDatabase(this.sinkTaskConfig.getContainersConfig().getDatabaseName()) .getContainer(containerName); CosmosThroughputControlHelper .tryEnableThroughputControl( container, this.throughputControlClient, this.sinkTaskConfig.getThroughputControlConfig()); List<SinkRecord> transformedRecords = sinkRecordTransformer.transform(containerName, entry.getValue()); this.cosmosWriter.write(container, transformedRecords); } }
class CosmosSinkTask extends SinkTask { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkTask.class); private CosmosSinkTaskConfig sinkTaskConfig; private CosmosAsyncClient cosmosClient; private CosmosAsyncClient throughputControlClient; private SinkRecordTransformer sinkRecordTransformer; private IWriter cosmosWriter; @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink task"); this.sinkTaskConfig = new CosmosSinkTaskConfig(props); this.cosmosClient = CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getAccountConfig()); this.throughputControlClient = this.getThroughputControlCosmosClient(); this.sinkRecordTransformer = new SinkRecordTransformer(this.sinkTaskConfig); if (this.sinkTaskConfig.getWriteConfig().isBulkEnabled()) { this.cosmosWriter = new KafkaCosmosBulkWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), this.context.errantRecordReporter()); } else { this.cosmosWriter = new KafkaCosmosPointWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), context.errantRecordReporter()); } } private CosmosAsyncClient getThroughputControlCosmosClient() { if (this.sinkTaskConfig.getThroughputControlConfig().isThroughputControlEnabled() && this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig() != null) { return CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig()); } else { return this.cosmosClient; } } @Override @Override public void stop() { LOGGER.info("Stopping Kafka CosmosDB sink task"); if (this.cosmosClient != null) { this.cosmosClient.close(); } } }
class CosmosSinkTask extends SinkTask { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkTask.class); private CosmosSinkTaskConfig sinkTaskConfig; private CosmosAsyncClient cosmosClient; private CosmosAsyncClient throughputControlClient; private SinkRecordTransformer sinkRecordTransformer; private IWriter cosmosWriter; @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink task"); this.sinkTaskConfig = new CosmosSinkTaskConfig(props); this.cosmosClient = CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getAccountConfig()); this.throughputControlClient = this.getThroughputControlCosmosClient(); this.sinkRecordTransformer = new SinkRecordTransformer(this.sinkTaskConfig); if (this.sinkTaskConfig.getWriteConfig().isBulkEnabled()) { this.cosmosWriter = new KafkaCosmosBulkWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), this.context.errantRecordReporter()); } else { this.cosmosWriter = new KafkaCosmosPointWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), context.errantRecordReporter()); } } private CosmosAsyncClient getThroughputControlCosmosClient() { if (this.sinkTaskConfig.getThroughputControlConfig().isThroughputControlEnabled() && this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig() != null) { return CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig()); } else { return this.cosmosClient; } } @Override @Override public void stop() { LOGGER.info("Stopping Kafka CosmosDB sink task"); if (this.cosmosClient != null) { this.cosmosClient.close(); } } }
And also for the above question: ``` What is the downside of having this config enabled for all containers? Ideally we should, however, we can do that post GA, thoughts? ``` you mean enable by default? but we can not do this it has to be an opt-in behavior as we need customer to provide the throughput control container
public void put(Collection<SinkRecord> records) { if (records == null || records.isEmpty()) { LOGGER.debug("No records to be written"); return; } LOGGER.debug("Sending {} records to be written", records.size()); Map<String, List<SinkRecord>> recordsByContainer = records.stream().collect( Collectors.groupingBy( record -> this.sinkTaskConfig .getContainersConfig() .getTopicToContainerMap() .getOrDefault(record.topic(), StringUtils.EMPTY))); if (recordsByContainer.containsKey(StringUtils.EMPTY)) { throw new IllegalStateException("There is no container defined for topics " + recordsByContainer.get(StringUtils.EMPTY)); } for (Map.Entry<String, List<SinkRecord>> entry : recordsByContainer.entrySet()) { String containerName = entry.getKey(); CosmosAsyncContainer container = this.cosmosClient .getDatabase(this.sinkTaskConfig.getContainersConfig().getDatabaseName()) .getContainer(containerName); CosmosThroughputControlHelper .tryEnableThroughputControl( container, this.throughputControlClient, this.sinkTaskConfig.getThroughputControlConfig()); List<SinkRecord> transformedRecords = sinkRecordTransformer.transform(containerName, entry.getValue()); this.cosmosWriter.write(container, transformedRecords); } }
.tryEnableThroughputControl(
public void put(Collection<SinkRecord> records) { if (records == null || records.isEmpty()) { LOGGER.debug("No records to be written"); return; } LOGGER.debug("Sending {} records to be written", records.size()); Map<String, List<SinkRecord>> recordsByContainer = records.stream().collect( Collectors.groupingBy( record -> this.sinkTaskConfig .getContainersConfig() .getTopicToContainerMap() .getOrDefault(record.topic(), StringUtils.EMPTY))); if (recordsByContainer.containsKey(StringUtils.EMPTY)) { throw new IllegalStateException("There is no container defined for topics " + recordsByContainer.get(StringUtils.EMPTY)); } for (Map.Entry<String, List<SinkRecord>> entry : recordsByContainer.entrySet()) { String containerName = entry.getKey(); CosmosAsyncContainer container = this.cosmosClient .getDatabase(this.sinkTaskConfig.getContainersConfig().getDatabaseName()) .getContainer(containerName); CosmosThroughputControlHelper .tryEnableThroughputControl( container, this.throughputControlClient, this.sinkTaskConfig.getThroughputControlConfig()); List<SinkRecord> transformedRecords = sinkRecordTransformer.transform(containerName, entry.getValue()); this.cosmosWriter.write(container, transformedRecords); } }
class CosmosSinkTask extends SinkTask { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkTask.class); private CosmosSinkTaskConfig sinkTaskConfig; private CosmosAsyncClient cosmosClient; private CosmosAsyncClient throughputControlClient; private SinkRecordTransformer sinkRecordTransformer; private IWriter cosmosWriter; @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink task"); this.sinkTaskConfig = new CosmosSinkTaskConfig(props); this.cosmosClient = CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getAccountConfig()); this.throughputControlClient = this.getThroughputControlCosmosClient(); this.sinkRecordTransformer = new SinkRecordTransformer(this.sinkTaskConfig); if (this.sinkTaskConfig.getWriteConfig().isBulkEnabled()) { this.cosmosWriter = new KafkaCosmosBulkWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), this.context.errantRecordReporter()); } else { this.cosmosWriter = new KafkaCosmosPointWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), context.errantRecordReporter()); } } private CosmosAsyncClient getThroughputControlCosmosClient() { if (this.sinkTaskConfig.getThroughputControlConfig().isThroughputControlEnabled() && this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig() != null) { return CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig()); } else { return this.cosmosClient; } } @Override @Override public void stop() { LOGGER.info("Stopping Kafka CosmosDB sink task"); if (this.cosmosClient != null) { this.cosmosClient.close(); } } }
class CosmosSinkTask extends SinkTask { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSinkTask.class); private CosmosSinkTaskConfig sinkTaskConfig; private CosmosAsyncClient cosmosClient; private CosmosAsyncClient throughputControlClient; private SinkRecordTransformer sinkRecordTransformer; private IWriter cosmosWriter; @Override public String version() { return KafkaCosmosConstants.CURRENT_VERSION; } @Override public void start(Map<String, String> props) { LOGGER.info("Starting the kafka cosmos sink task"); this.sinkTaskConfig = new CosmosSinkTaskConfig(props); this.cosmosClient = CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getAccountConfig()); this.throughputControlClient = this.getThroughputControlCosmosClient(); this.sinkRecordTransformer = new SinkRecordTransformer(this.sinkTaskConfig); if (this.sinkTaskConfig.getWriteConfig().isBulkEnabled()) { this.cosmosWriter = new KafkaCosmosBulkWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), this.context.errantRecordReporter()); } else { this.cosmosWriter = new KafkaCosmosPointWriter( this.sinkTaskConfig.getWriteConfig(), this.sinkTaskConfig.getThroughputControlConfig(), context.errantRecordReporter()); } } private CosmosAsyncClient getThroughputControlCosmosClient() { if (this.sinkTaskConfig.getThroughputControlConfig().isThroughputControlEnabled() && this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig() != null) { return CosmosClientStore.getCosmosClient(this.sinkTaskConfig.getThroughputControlConfig().getThroughputControlAccountConfig()); } else { return this.cosmosClient; } } @Override @Override public void stop() { LOGGER.info("Stopping Kafka CosmosDB sink task"); if (this.cosmosClient != null) { this.cosmosClient.close(); } } }
SSL socket extends Socket, so we can just call close here without type checking
public void closeSocketAndStreams() throws IOException { if (socketInputStream != null) { socketInputStream.close(); } if (socketOutputStream != null) { socketOutputStream.close(); } if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; sslSocket.close(); } else { socket.close(); } }
sslSocket.close();
public void closeSocketAndStreams() throws IOException { if (socketInputStream != null) { socketInputStream.close(); } if (socketOutputStream != null) { socketOutputStream.close(); } socket.close(); }
class SocketConnection { private final Socket socket; private OutputStream socketOutputStream; private BufferedInputStream socketInputStream; private final SocketConnectionProperties connectionProperties; private boolean canBeReused = false; SocketConnection(Socket socket, SocketConnectionProperties socketConnectionProperties) { this.socket = socket; this.connectionProperties = socketConnectionProperties; } /** * Get the output stream of the socket * @return the output stream * @throws IOException if an I/O error occurs */ public OutputStream getSocketOutputStream() throws IOException { if (socketOutputStream == null) { socketOutputStream = socket.getOutputStream(); } return socketOutputStream; } /** * Get the input stream of the socket * @return the input stream * @throws IOException if an I/O error occurs */ public BufferedInputStream getSocketInputStream() throws IOException { if (socketInputStream == null) { socketInputStream = new BufferedInputStream(socket.getInputStream()); } return socketInputStream; } /** * Mark the connection as available for reuse */ public void markAvailableForReuse() { this.canBeReused = true; } /** * Close the socket and its streams * @throws IOException if an I/O error occurs */ Socket getSocket() { return socket; } SocketConnectionProperties getConnectionProperties() { return connectionProperties; } /** * Check if the connection can be reused * @return true if the connection can be reused, false otherwise */ boolean canBeReused() { return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } /** * Checks the status of connection is reused * @return true if the connection is reused, false otherwise */ public boolean isReused() { return canBeReused; } /** * Class to hold the properties of the socket connection */ public static final class SocketConnectionProperties { private final URL requestUrl; private final String host; private final String port; /** * Creates a new instance of SocketConnectionProperties * * @param requestUrl the HTTP request url * @param host the host name * @param port the port number */ public SocketConnectionProperties(URL requestUrl, String host, String port) { this.requestUrl = requestUrl; this.host = host; this.port = port; } @Override public boolean equals(Object other) { if (other instanceof SocketConnectionProperties) { SocketConnectionProperties that = (SocketConnectionProperties) other; return Objects.equals(this.host, that.host) && this.port.equals(that.port); } return false; } @Override public int hashCode() { return Objects.hash(host, port); } /** * Get the HTTP request URL * @return the HTTP request URL */ public URL getRequestUrl() { return requestUrl; } } }
class SocketConnection { private final Socket socket; private OutputStream socketOutputStream; private BufferedInputStream socketInputStream; private final SocketConnectionProperties connectionProperties; private boolean canBeReused = false; SocketConnection(Socket socket, SocketConnectionProperties socketConnectionProperties) { this.socket = socket; this.connectionProperties = socketConnectionProperties; } /** * Get the output stream of the socket * @return the output stream * @throws IOException if an I/O error occurs */ public OutputStream getSocketOutputStream() throws IOException { if (socketOutputStream == null) { socketOutputStream = socket.getOutputStream(); } return socketOutputStream; } /** * Get the input stream of the socket * @return the input stream * @throws IOException if an I/O error occurs */ public BufferedInputStream getSocketInputStream() throws IOException { if (socketInputStream == null) { socketInputStream = new BufferedInputStream(socket.getInputStream()); } return socketInputStream; } /** * Mark the connection as available for reuse */ public void markAvailableForReuse() { this.canBeReused = true; } /** * Close the socket and its streams * @throws IOException if an I/O error occurs */ Socket getSocket() { return socket; } SocketConnectionProperties getConnectionProperties() { return connectionProperties; } /** * Check if the connection can be reused * @return true if the connection can be reused, false otherwise */ boolean canBeReused() { return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } /** * Class to hold the properties of the socket connection */ public static final class SocketConnectionProperties { private final String protocol; private final String host; private final int port; private final SSLSocketFactory sslSocketFactory; private final int readTimeout; /** * Creates a new instance of SocketConnectionProperties * * @param protocol the HTTP request protocol * @param host the host name * @param port the port number * @param sslSocketFactory the SSL socket factory * @param readTimeout the read timeout */ public SocketConnectionProperties(String protocol, String host, int port, SSLSocketFactory sslSocketFactory, int readTimeout) { this.protocol = protocol; this.host = host; this.port = port; this.sslSocketFactory = sslSocketFactory; this.readTimeout = readTimeout; } @Override public boolean equals(Object other) { if (other instanceof SocketConnectionProperties) { SocketConnectionProperties that = (SocketConnectionProperties) other; boolean p = Objects.equals(this.host, that.host) && this.port == that.port && this.sslSocketFactory == that.sslSocketFactory && this.protocol.equals(that.protocol) && this.readTimeout == that.readTimeout; return p; } return false; } @Override public int hashCode() { return Objects.hash(host, port); } /** * Get the HTTP request protocol * @return the HTTP request protocol */ public String getProtocol() { return protocol; } /** * Get the SSL socket factory * @return SSL socket factory */ public SSLSocketFactory getSslSocketFactory() { return sslSocketFactory; } /** * Get the host name * @return the host name */ public String getHost() { return host; } /** * Get the port number * @return the port number */ public int getPort() { return port; } /** * Get the read timeout * @return the read timeout */ public int getReadTimeout() { return readTimeout; } } }
Closing the socket will also close the streams
public void closeSocketAndStreams() throws IOException { if (socketInputStream != null) { socketInputStream.close(); } if (socketOutputStream != null) { socketOutputStream.close(); } if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; sslSocket.close(); } else { socket.close(); } }
}
public void closeSocketAndStreams() throws IOException { if (socketInputStream != null) { socketInputStream.close(); } if (socketOutputStream != null) { socketOutputStream.close(); } socket.close(); }
class SocketConnection { private final Socket socket; private OutputStream socketOutputStream; private BufferedInputStream socketInputStream; private final SocketConnectionProperties connectionProperties; private boolean canBeReused = false; SocketConnection(Socket socket, SocketConnectionProperties socketConnectionProperties) { this.socket = socket; this.connectionProperties = socketConnectionProperties; } /** * Get the output stream of the socket * @return the output stream * @throws IOException if an I/O error occurs */ public OutputStream getSocketOutputStream() throws IOException { if (socketOutputStream == null) { socketOutputStream = socket.getOutputStream(); } return socketOutputStream; } /** * Get the input stream of the socket * @return the input stream * @throws IOException if an I/O error occurs */ public BufferedInputStream getSocketInputStream() throws IOException { if (socketInputStream == null) { socketInputStream = new BufferedInputStream(socket.getInputStream()); } return socketInputStream; } /** * Mark the connection as available for reuse */ public void markAvailableForReuse() { this.canBeReused = true; } /** * Close the socket and its streams * @throws IOException if an I/O error occurs */ Socket getSocket() { return socket; } SocketConnectionProperties getConnectionProperties() { return connectionProperties; } /** * Check if the connection can be reused * @return true if the connection can be reused, false otherwise */ boolean canBeReused() { return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } /** * Checks the status of connection is reused * @return true if the connection is reused, false otherwise */ public boolean isReused() { return canBeReused; } /** * Class to hold the properties of the socket connection */ public static final class SocketConnectionProperties { private final URL requestUrl; private final String host; private final String port; /** * Creates a new instance of SocketConnectionProperties * * @param requestUrl the HTTP request url * @param host the host name * @param port the port number */ public SocketConnectionProperties(URL requestUrl, String host, String port) { this.requestUrl = requestUrl; this.host = host; this.port = port; } @Override public boolean equals(Object other) { if (other instanceof SocketConnectionProperties) { SocketConnectionProperties that = (SocketConnectionProperties) other; return Objects.equals(this.host, that.host) && this.port.equals(that.port); } return false; } @Override public int hashCode() { return Objects.hash(host, port); } /** * Get the HTTP request URL * @return the HTTP request URL */ public URL getRequestUrl() { return requestUrl; } } }
class SocketConnection { private final Socket socket; private OutputStream socketOutputStream; private BufferedInputStream socketInputStream; private final SocketConnectionProperties connectionProperties; private boolean canBeReused = false; SocketConnection(Socket socket, SocketConnectionProperties socketConnectionProperties) { this.socket = socket; this.connectionProperties = socketConnectionProperties; } /** * Get the output stream of the socket * @return the output stream * @throws IOException if an I/O error occurs */ public OutputStream getSocketOutputStream() throws IOException { if (socketOutputStream == null) { socketOutputStream = socket.getOutputStream(); } return socketOutputStream; } /** * Get the input stream of the socket * @return the input stream * @throws IOException if an I/O error occurs */ public BufferedInputStream getSocketInputStream() throws IOException { if (socketInputStream == null) { socketInputStream = new BufferedInputStream(socket.getInputStream()); } return socketInputStream; } /** * Mark the connection as available for reuse */ public void markAvailableForReuse() { this.canBeReused = true; } /** * Close the socket and its streams * @throws IOException if an I/O error occurs */ Socket getSocket() { return socket; } SocketConnectionProperties getConnectionProperties() { return connectionProperties; } /** * Check if the connection can be reused * @return true if the connection can be reused, false otherwise */ boolean canBeReused() { return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } /** * Class to hold the properties of the socket connection */ public static final class SocketConnectionProperties { private final String protocol; private final String host; private final int port; private final SSLSocketFactory sslSocketFactory; private final int readTimeout; /** * Creates a new instance of SocketConnectionProperties * * @param protocol the HTTP request protocol * @param host the host name * @param port the port number * @param sslSocketFactory the SSL socket factory * @param readTimeout the read timeout */ public SocketConnectionProperties(String protocol, String host, int port, SSLSocketFactory sslSocketFactory, int readTimeout) { this.protocol = protocol; this.host = host; this.port = port; this.sslSocketFactory = sslSocketFactory; this.readTimeout = readTimeout; } @Override public boolean equals(Object other) { if (other instanceof SocketConnectionProperties) { SocketConnectionProperties that = (SocketConnectionProperties) other; boolean p = Objects.equals(this.host, that.host) && this.port == that.port && this.sslSocketFactory == that.sslSocketFactory && this.protocol.equals(that.protocol) && this.readTimeout == that.readTimeout; return p; } return false; } @Override public int hashCode() { return Objects.hash(host, port); } /** * Get the HTTP request protocol * @return the HTTP request protocol */ public String getProtocol() { return protocol; } /** * Get the SSL socket factory * @return SSL socket factory */ public SSLSocketFactory getSslSocketFactory() { return sslSocketFactory; } /** * Get the host name * @return the host name */ public String getHost() { return host; } /** * Get the port number * @return the port number */ public int getPort() { return port; } /** * Get the read timeout * @return the read timeout */ public int getReadTimeout() { return readTimeout; } } }
This will break the perf scenarios as we still have get defined
public static void main(String[] args) { TelemetryHelper.init(); PerfStressProgram.run(new Class<?>[]{ HttpPatch.class, }, args); }
public static void main(String[] args) { TelemetryHelper.init(); PerfStressProgram.run(new Class<?>[]{ HttpGet.class, HttpPatch.class, }, args); }
class App { /** * Main method to invoke other stress tests. * @param args the input arguments */ }
class App { /** * Main method to invoke other stress tests. * @param args the input arguments */ }
Bind to a random port, we can't guarantee 8080 will be available
public static void setup() { if (myServerSocket != null && !myServerSocket.isClosed()) { try { myServerSocket.close(); } catch (IOException e) { e.printStackTrace(); } } server = new Thread(() -> { try { ServerSocket myServer = new ServerSocket(); myServer.setReuseAddress(true); myServer.bind(new java.net.InetSocketAddress(PORT)); myServerSocket = myServer.accept(); while (keepRunning) { BufferedReader br = new BufferedReader(new InputStreamReader(myServerSocket.getInputStream())); DataOutputStream out = new DataOutputStream(myServerSocket.getOutputStream()); while (keepRunning) { String line; StringBuilder request = new StringBuilder(); while ((line = br.readLine()) != null && !line.isEmpty()) { request.append(line).append("\n"); } out.writeBytes("HTTP/1.1 200 OK\n\n"); out.flush(); } } } catch (IOException e) { e.printStackTrace(); } }); server.start(); }
myServer.bind(new java.net.InetSocketAddress(PORT));
public static void setup() throws IOException { if (myServerSocket != null && !myServerSocket.isClosed()) { try { myServerSocket.close(); } catch (IOException e) { e.printStackTrace(); } } ServerSocket myServer = new ServerSocket(0); int port = myServer.getLocalPort(); myServer.setReuseAddress(true); socketConnectionProperties = new SocketConnectionProperties("http", "localhost", port, null, 5000); server = new Thread(() -> { try { myServerSocket = myServer.accept(); while (!Thread.currentThread().isInterrupted() && keepRunning) { BufferedReader br = new BufferedReader(new InputStreamReader(myServerSocket.getInputStream())); DataOutputStream out = new DataOutputStream(myServerSocket.getOutputStream()); while (keepRunning) { String line; StringBuilder request = new StringBuilder(); while ((line = br.readLine()) != null && !line.isEmpty()) { request.append(line).append("\n"); } out.writeBytes("HTTP/1.1 200 OK\n\n"); out.flush(); } } } catch (IOException e) { e.printStackTrace(); } }); server.start(); }
class SocketConnectionCacheTest { private static Socket myServerSocket; private static Thread server; private static final int PORT = 8080; private static volatile boolean keepRunning = true; private static final SocketConnectionProperties SOCKET_PROPERTIES; static { try { SOCKET_PROPERTIES = new SocketConnectionProperties(new URL("http: } catch (MalformedURLException e) { throw new RuntimeException(e); } } @BeforeAll @AfterAll @SuppressWarnings("deprecation") public static void tearDown() throws IOException, InterruptedException { keepRunning = false; if (myServerSocket != null) { server.stop(); if (!myServerSocket.isClosed()) { myServerSocket.close(); } myServerSocket = null; } Thread.sleep(1000); } @Test @Order(1) void testGetInstance() { SocketConnectionCache.clearCache(); SocketConnectionCache instance1 = SocketConnectionCache.getInstance(true, 10, 5000); SocketConnectionCache instance2 = SocketConnectionCache.getInstance(true, 10, 5000); assertSame(instance1, instance2, "Instances are not the same"); } @Test @Order(2) void testGetConnectionReturnsNewConnection() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10, 5000); try { SocketConnection connection = instance.get(SOCKET_PROPERTIES); assertNotNull(connection, "Connection is null"); } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } } @Test @Order(3) void testReuseConnection() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10, 5000); try { SocketConnection connection = instance.get(SOCKET_PROPERTIES); instance.reuseConnection(connection); assertTrue(!connection.getSocket().isClosed(), "Connection is kept open"); SocketConnection connection2 = instance.get(SOCKET_PROPERTIES); assertSame(connection, connection2, "Connections are not the same"); } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } } @SuppressWarnings("unchecked") @Test @Order(4) void testConnectionPoolSize() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10, 5000); try { for (int i = 0; i < 10; i++) { SocketConnection connection = instance.get(SOCKET_PROPERTIES); instance.reuseConnection(connection); } Field connectionPoolField = SocketConnectionCache.class.getDeclaredField("CONNECTION_POOL"); connectionPoolField.setAccessible(true); Map<SocketConnectionProperties, List<SocketConnection>> connectionPool = (Map<SocketConnectionProperties, List<SocketConnection>>) connectionPoolField.get(instance); int poolSize = connectionPool.get(SOCKET_PROPERTIES).size(); assertEquals(1, poolSize, "Connection pool size is not as expected"); } catch (IOException | NoSuchFieldException | IllegalAccessException e) { fail("Exception thrown: " + e.getMessage()); } } @SuppressWarnings("unchecked") @Test @Order(5) void testConnectionPoolSizeMultipleThreads() { SocketConnectionCache.clearCache(); int maxConnections = 5; SocketConnectionCache instance = SocketConnectionCache.getInstance(true, maxConnections, 5000); ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) { executorService.submit(() -> { try { SocketConnection connection = instance.get(SOCKET_PROPERTIES); instance.reuseConnection(connection); } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } }); } executorService.shutdown(); try { executorService.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { fail("Test interrupted: " + e.getMessage()); } try { Field connectionPoolField = SocketConnectionCache.class.getDeclaredField("CONNECTION_POOL"); connectionPoolField.setAccessible(true); Map<SocketConnectionProperties, List<SocketConnection>> connectionPool = (Map<SocketConnectionProperties, List<SocketConnection>>) connectionPoolField.get(instance); int poolSize = connectionPool.get(SOCKET_PROPERTIES).size(); assertEquals(maxConnections, poolSize, "Connection pool size is not as expected"); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Exception thrown: " + e.getMessage()); } } @Test @Order(6) void testKeepConnectionAliveFalse() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(false, 10, 5000); try { SocketConnection connection1 = instance.get(SOCKET_PROPERTIES); instance.reuseConnection(connection1); SocketConnection connection2 = instance.get(SOCKET_PROPERTIES); assertNotSame(connection1, connection2, "Connections are the same"); } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } } @SuppressWarnings("unchecked") @Test @Order(7) void testReuseClosedConnection() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10, 5000); try { SocketConnection connection = instance.get(SOCKET_PROPERTIES); connection.getSocket().close(); instance.reuseConnection(connection); try { Field connectionPoolField = SocketConnectionCache.class.getDeclaredField("CONNECTION_POOL"); connectionPoolField.setAccessible(true); Map<SocketConnectionProperties, List<SocketConnection>> connectionPool = (Map<SocketConnectionProperties, List<SocketConnection>>) connectionPoolField.get(instance); int poolSize = connectionPool.get(SOCKET_PROPERTIES).size(); assertEquals(0, poolSize, "Connection pool size should be 0 as connection is closed"); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Exception thrown: " + e.getMessage()); } } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } } @Test @Order(8) void testReadTimeout() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10, 5000); new Thread(() -> { try (ServerSocket serverSocket = new ServerSocket(8081)) { Socket clientSocket = serverSocket.accept(); Thread.sleep(6000); DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); out.writeBytes("HTTP/1.1 200 OK\n\n"); out.flush(); } catch (IOException | InterruptedException e) { fail("Exception thrown: " + e.getMessage()); } }).start(); assertThrows(SocketTimeoutException.class, () -> { SocketConnection connection = instance.get( new SocketConnectionProperties(new URL("http: BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getSocket().getInputStream())); reader.readLine(); }, "Expected readLine() to throw, but it didn't"); } }
class SocketConnectionCacheTest { private static Socket myServerSocket; private static Thread server; private static volatile boolean keepRunning = true; private static SocketConnectionProperties socketConnectionProperties; @BeforeAll @AfterAll public static void tearDown() throws IOException, InterruptedException { keepRunning = false; if (myServerSocket != null) { server.interrupt(); if (!myServerSocket.isClosed()) { myServerSocket.close(); } myServerSocket = null; } Thread.sleep(1000); } @Test @Order(1) void testGetInstance() { SocketConnectionCache.clearCache(); SocketConnectionCache instance1 = SocketConnectionCache.getInstance(true, 10); SocketConnectionCache instance2 = SocketConnectionCache.getInstance(true, 10); assertSame(instance1, instance2, "Instances are not the same"); } @Test @Order(2) void testGetConnectionReturnsNewConnection() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10); try { SocketConnection connection = instance.get(socketConnectionProperties); assertNotNull(connection, "Connection is null"); } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } } @Test @Order(3) void testReuseConnection() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10); try { SocketConnection connection = instance.get(socketConnectionProperties); instance.reuseConnection(connection); assertTrue(!connection.getSocket().isClosed(), "Connection is kept open"); SocketConnection connection2 = instance.get(socketConnectionProperties); assertSame(connection, connection2, "Connections are not the same"); } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } } @SuppressWarnings("unchecked") @Test @Order(4) void testConnectionPoolSize() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10); try { for (int i = 0; i < 10; i++) { SocketConnection connection = instance.get(socketConnectionProperties); instance.reuseConnection(connection); } Field connectionPoolField = SocketConnectionCache.class.getDeclaredField("CONNECTION_POOL"); connectionPoolField.setAccessible(true); Map<SocketConnectionProperties, List<SocketConnection>> connectionPool = (Map<SocketConnectionProperties, List<SocketConnection>>) connectionPoolField.get(instance); int poolSize = connectionPool.get(socketConnectionProperties).size(); assertEquals(1, poolSize, "Connection pool size is not as expected"); } catch (IOException | NoSuchFieldException | IllegalAccessException e) { fail("Exception thrown: " + e.getMessage()); } } @SuppressWarnings("unchecked") @Test @Order(5) void testConnectionPoolSizeMultipleThreads() { SocketConnectionCache.clearCache(); int maxConnections = 5; SocketConnectionCache instance = SocketConnectionCache.getInstance(true, maxConnections); ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) { executorService.submit(() -> { try { SocketConnection connection = instance.get(socketConnectionProperties); instance.reuseConnection(connection); } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } }); } executorService.shutdown(); try { executorService.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { fail("Test interrupted: " + e.getMessage()); } try { Field connectionPoolField = SocketConnectionCache.class.getDeclaredField("CONNECTION_POOL"); connectionPoolField.setAccessible(true); Map<SocketConnectionProperties, List<SocketConnection>> connectionPool = (Map<SocketConnectionProperties, List<SocketConnection>>) connectionPoolField.get(instance); int poolSize = connectionPool.get(socketConnectionProperties).size(); assertTrue(poolSize >= 1 && poolSize <= 5, "Connection pool size is not within the expected range (1-5)"); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Exception thrown: " + e.getMessage()); } } @Test @Order(6) void testKeepConnectionAliveFalse() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(false, 10); try { SocketConnection connection1 = instance.get(socketConnectionProperties); instance.reuseConnection(connection1); SocketConnection connection2 = instance.get(socketConnectionProperties); assertNotSame(connection1, connection2, "Connections are the same"); } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } } @SuppressWarnings("unchecked") @Test @Order(7) void testReuseClosedConnection() { SocketConnectionCache.clearCache(); SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10); try { SocketConnection connection = instance.get(socketConnectionProperties); connection.getSocket().close(); instance.reuseConnection(connection); try { Field connectionPoolField = SocketConnectionCache.class.getDeclaredField("CONNECTION_POOL"); connectionPoolField.setAccessible(true); Map<SocketConnectionProperties, List<SocketConnection>> connectionPool = (Map<SocketConnectionProperties, List<SocketConnection>>) connectionPoolField.get(instance); int poolSize = connectionPool.get(socketConnectionProperties).size(); assertEquals(0, poolSize, "Connection pool size should be 0 as connection is closed"); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Exception thrown: " + e.getMessage()); } } catch (IOException e) { fail("Exception thrown: " + e.getMessage()); } } @Test @Order(8) public void testSocketReadTimeout() { SocketConnectionCache instance = SocketConnectionCache.getInstance(true, 10); try { SocketConnection connection = instance.get(socketConnectionProperties); Socket socket = connection.getSocket(); assertEquals(5000, socket.getSoTimeout(), "Socket read timeout is not as expected"); } catch (IOException e) { e.printStackTrace(); } } }
nit: we shouldn't be using `synchronized`, this reduces scalability when using virtual threads. We should look into using things like `ReentrantLock` or `Semaphore` for concurrency control.
public SocketConnection get(SocketConnectionProperties socketConnectionProperties) throws IOException { SocketConnection connection = null; synchronized (CONNECTION_POOL) { List<SocketConnection> connections = CONNECTION_POOL.get(socketConnectionProperties); while (!CoreUtils.isNullOrEmpty(connections)) { connection = connections.remove(connections.size() - 1); if (connections.isEmpty()) { CONNECTION_POOL.remove(socketConnectionProperties); connections = null; } else { CONNECTION_POOL.put(socketConnectionProperties, connections); } if (connection.canBeReused()) { return connection; } } } if (connection == null) { connection = getSocketSocketConnection(socketConnectionProperties, readTimeout, keepConnectionAlive); } synchronized (CONNECTION_POOL) { List<SocketConnection> connections = CONNECTION_POOL.get(socketConnectionProperties); if (connections == null) { connections = new ArrayList<>(); CONNECTION_POOL.put(socketConnectionProperties, connections); } } return connection; }
synchronized (CONNECTION_POOL) {
public SocketConnection get(SocketConnectionProperties socketConnectionProperties) throws IOException { SocketConnection connection = null; LOCK.lock(); try { List<SocketConnection> connections = CONNECTION_POOL.get(socketConnectionProperties); while (!CoreUtils.isNullOrEmpty(connections)) { connection = connections.remove(connections.size() - 1); if (connections.isEmpty()) { CONNECTION_POOL.remove(socketConnectionProperties); connections = null; } else { CONNECTION_POOL.put(socketConnectionProperties, connections); } if (connection.canBeReused()) { return connection; } } } finally { LOCK.unlock(); } if (connection == null) { connection = getSocketSocketConnection(socketConnectionProperties, keepConnectionAlive); } LOCK.lock(); try { List<SocketConnection> connections = CONNECTION_POOL.get(socketConnectionProperties); if (connections == null) { connections = new ArrayList<>(); CONNECTION_POOL.put(socketConnectionProperties, connections); } } finally { LOCK.unlock(); } return connection; }
class SocketConnectionCache { private static ClientLogger logger = new ClientLogger(SocketConnectionCache.class); private static SocketConnectionCache instance; private static final Map<SocketConnectionProperties, List<SocketConnection>> CONNECTION_POOL = new ConcurrentHashMap<>(); private final int readTimeout; private final boolean keepConnectionAlive; private final int maxConnections; private long readPos = 0; private SocketConnectionCache(boolean connectionKeepAlive, int maximumConnections, int readTimeout) { this.keepConnectionAlive = connectionKeepAlive; this.maxConnections = maximumConnections; this.readTimeout = readTimeout; } /** * Get the instance of the SocketConnectionCache (Singleton) * @param connectionKeepAlive boolean to keep the connection alive * @param maximumConnections maximum number of connections to keep alive * @param readTimeout read timeout for the connection * @return the instance of the SocketConnectionCache if it exists, else create a new one */ public static synchronized SocketConnectionCache getInstance(boolean connectionKeepAlive, int maximumConnections, int readTimeout) { if (instance == null) { instance = new SocketConnectionCache(connectionKeepAlive, maximumConnections, readTimeout); } return instance; } /** * Get a {@link SocketConnection connection} from the cache based on the {@link SocketConnectionProperties} * or create a new one * @param socketConnectionProperties the properties of the connection * @return the connection * @throws IOException if an I/O error occurs */ /** * Clear the cache of connections */ static void clearCache() { synchronized (CONNECTION_POOL) { CONNECTION_POOL.clear(); } instance = null; } /** * Reuse the {@link SocketConnection connection} if it can be reused, else close the connection * @param connection the connection to be reused * @throws IOException if an I/O error occurs */ public void reuseConnection(SocketConnection connection) throws IOException { if (maxConnections > 0 && keepConnectionAlive && connection.canBeReused()) { SocketConnectionProperties connectionProperties = connection.getConnectionProperties(); synchronized (CONNECTION_POOL) { List<SocketConnection> connections = CONNECTION_POOL.get(connectionProperties); if (connections == null) { connections = new ArrayList<SocketConnection>(); CONNECTION_POOL.put(connectionProperties, connections); } if (connections.size() < maxConnections) { BufferedInputStream is = connection.getSocketInputStream(); skipRemaining(is); connection.markAvailableForReuse(); connections.add(connection); CONNECTION_POOL.put(connectionProperties, connections); } return; } } connection.closeSocketAndStreams(); } private static SocketConnection getSocketSocketConnection(SocketConnectionProperties socketConnectionProperties, int readTimeout, boolean keepConnectionAlive) throws IOException { URL requestUrl = socketConnectionProperties.getRequestUrl(); String protocol = requestUrl.getProtocol(); String host = requestUrl.getHost(); int port = requestUrl.getPort(); Socket socket; if ("https".equals(protocol)) { SSLSocketFactory sslSocketFactory = socketConnectionProperties.getSslSocketFactory(); socket = sslSocketFactory.createSocket(host, port); } else { socket = new Socket(host, port); } if (keepConnectionAlive) { socket.setKeepAlive(true); socket.setReuseAddress(true); } if (readTimeout != -1) { socket.setSoTimeout(readTimeout); } return new SocketConnection(socket, socketConnectionProperties); } private void skipRemaining(InputStream is) throws IOException { long count = is.available(); readPos += count; long pos = 0; int chunkSize = 4096; while (pos < count) { long toSkip = Math.min(chunkSize, count - pos); long skipped = is.skip(toSkip); if (skipped == -1) { logger.logThrowableAsError(new IOException("No data, can't skip " + count + " bytes")); } pos += skipped; } } }
class SocketConnectionCache { private static final ClientLogger LOGGER = new ClientLogger(SocketConnectionCache.class); private static SocketConnectionCache instance; private static final ReentrantLock LOCK = new ReentrantLock(); private static final Map<SocketConnectionProperties, List<SocketConnection>> CONNECTION_POOL = new ConcurrentHashMap<>(); private final boolean keepConnectionAlive; private final int maxConnections; private SocketConnectionCache(boolean connectionKeepAlive, int maximumConnections) { this.keepConnectionAlive = connectionKeepAlive; this.maxConnections = maximumConnections; } /** * Get the instance of the SocketConnectionCache (Singleton) * * @param connectionKeepAlive boolean to keep the connection alive * @param maximumConnections maximum number of connections to keep alive * @return the instance of the SocketConnectionCache if it exists, else create a new one */ public static SocketConnectionCache getInstance(boolean connectionKeepAlive, int maximumConnections) { LOCK.lock(); try { if (instance == null) { instance = new SocketConnectionCache(connectionKeepAlive, maximumConnections); } return instance; } finally { LOCK.unlock(); } } /** * Get a {@link SocketConnection connection} from the cache based on the {@link SocketConnectionProperties} * or create a new one * @param socketConnectionProperties the properties of the connection * @return the connection * @throws IOException if an I/O error occurs */ /** * Clear the cache of connections */ static void clearCache() { LOCK.lock(); try { CONNECTION_POOL.clear(); } finally { LOCK.unlock(); } instance = null; } /** * Reuse the {@link SocketConnection connection} if it can be reused, else close the connection * @param connection the connection to be reused * @throws IOException if an I/O error occurs */ public void reuseConnection(SocketConnection connection) throws IOException { if (maxConnections > 0 && keepConnectionAlive && connection.canBeReused()) { SocketConnectionProperties connectionProperties = connection.getConnectionProperties(); LOCK.lock(); try { List<SocketConnection> connections = CONNECTION_POOL.get(connectionProperties); if (connections == null) { connections = new ArrayList<SocketConnection>(); CONNECTION_POOL.put(connectionProperties, connections); } if (connections.size() < maxConnections) { BufferedInputStream is = connection.getSocketInputStream(); skipRemaining(is); connection.markAvailableForReuse(); connections.add(connection); CONNECTION_POOL.put(connectionProperties, connections); } return; } finally { LOCK.unlock(); } } connection.closeSocketAndStreams(); } private static SocketConnection getSocketSocketConnection(SocketConnectionProperties socketConnectionProperties, boolean keepConnectionAlive) throws IOException { String protocol = socketConnectionProperties.getProtocol(); String host = socketConnectionProperties.getHost(); int port = socketConnectionProperties.getPort(); int readTimeout = socketConnectionProperties.getReadTimeout(); Socket socket; if ("https".equals(protocol)) { SSLSocketFactory sslSocketFactory = socketConnectionProperties.getSslSocketFactory(); socket = sslSocketFactory.createSocket(host, port); } else { socket = new Socket(host, port); } if (keepConnectionAlive) { socket.setKeepAlive(true); socket.setReuseAddress(true); } if (readTimeout != -1) { socket.setSoTimeout(readTimeout); } return new SocketConnection(socket, socketConnectionProperties); } private void skipRemaining(InputStream is) throws IOException { long count = is.available(); long pos = 0; int chunkSize = 4096; while (pos < count) { long toSkip = Math.min(chunkSize, count - pos); long skipped = is.skip(toSkip); if (skipped == -1) { LOGGER.logThrowableAsError(new IOException("No data, can't skip " + count + " bytes")); } pos += skipped; } } }
One thing we may need to look at in the future for performance is reading in chunks, reading byte-by-byte off the network will be costly.
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { throw new IllegalStateException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { throw new IllegalStateException("Unexpected response from server. Status : " + statusLine); } return Integer.parseInt(parts[1]); }
while ((b = inputStream.read()) != -1 && b != '\n') {
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { inputStream.close(); throw new ProtocolException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { inputStream.close(); throw new ProtocolException(("Unexpected response from server. Status : " + statusLine)); } return Integer.parseInt(parts[1]); }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { contentLength = -1; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { return null; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } if (totalBytesRead != contentLength) { try { inputStream.close(); } catch (IOException e) { } throw new IOException("Read " + totalBytesRead + " bytes but expected " + contentLength); } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
Let's use `ProtocolException` here and when there isn't a status code
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { throw new IllegalStateException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { throw new IllegalStateException("Unexpected response from server. Status : " + statusLine); } return Integer.parseInt(parts[1]); }
throw new IllegalStateException("Unexpected response from server.");
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { inputStream.close(); throw new ProtocolException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { inputStream.close(); throw new ProtocolException(("Unexpected response from server. Status : " + statusLine)); } return Integer.parseInt(parts[1]); }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { contentLength = -1; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { return null; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } if (totalBytesRead != contentLength) { try { inputStream.close(); } catch (IOException e) { } throw new IOException("Read " + totalBytesRead + " bytes but expected " + contentLength); } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
When exceptions are thrown during processing, are we closing the connection?
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { throw new IllegalStateException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { throw new IllegalStateException("Unexpected response from server. Status : " + statusLine); } return Integer.parseInt(parts[1]); }
throw new IllegalStateException("Unexpected response from server. Status : " + statusLine);
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { inputStream.close(); throw new ProtocolException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { inputStream.close(); throw new ProtocolException(("Unexpected response from server. Status : " + statusLine)); } return Integer.parseInt(parts[1]); }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { contentLength = -1; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { return null; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } if (totalBytesRead != contentLength) { try { inputStream.close(); } catch (IOException e) { } throw new IOException("Read " + totalBytesRead + " bytes but expected " + contentLength); } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
Aren't Protocol Exceptions usually binding exceptions whereas this would be a response related exception..
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { throw new IllegalStateException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { throw new IllegalStateException("Unexpected response from server. Status : " + statusLine); } return Integer.parseInt(parts[1]); }
throw new IllegalStateException("Unexpected response from server.");
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { inputStream.close(); throw new ProtocolException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { inputStream.close(); throw new ProtocolException(("Unexpected response from server. Status : " + statusLine)); } return Integer.parseInt(parts[1]); }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { contentLength = -1; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { return null; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } if (totalBytesRead != contentLength) { try { inputStream.close(); } catch (IOException e) { } throw new IOException("Read " + totalBytesRead + " bytes but expected " + contentLength); } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
Since we are dealing with persistent connections and inputstreams, we should be better off reading byte-by-byte rather than buffering readers or readLines I was thinking. What could be the alternative otherwise?
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { throw new IllegalStateException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { throw new IllegalStateException("Unexpected response from server. Status : " + statusLine); } return Integer.parseInt(parts[1]); }
while ((b = inputStream.read()) != -1 && b != '\n') {
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { inputStream.close(); throw new ProtocolException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { inputStream.close(); throw new ProtocolException(("Unexpected response from server. Status : " + statusLine)); } return Integer.parseInt(parts[1]); }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { contentLength = -1; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { return null; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } if (totalBytesRead != contentLength) { try { inputStream.close(); } catch (IOException e) { } throw new IOException("Read " + totalBytesRead + " bytes but expected " + contentLength); } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
It's what the JDK HttpClient uses in this case, which is why I was recommending it.
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { throw new IllegalStateException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { throw new IllegalStateException("Unexpected response from server. Status : " + statusLine); } return Integer.parseInt(parts[1]); }
throw new IllegalStateException("Unexpected response from server.");
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { inputStream.close(); throw new ProtocolException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { inputStream.close(); throw new ProtocolException(("Unexpected response from server. Status : " + statusLine)); } return Integer.parseInt(parts[1]); }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { contentLength = -1; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { return null; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } if (totalBytesRead != contentLength) { try { inputStream.close(); } catch (IOException e) { } throw new IOException("Read " + totalBytesRead + " bytes but expected " + contentLength); } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
I believe the Socket stream will return `-1` even if the connection can be reused later.
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { throw new IllegalStateException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { throw new IllegalStateException("Unexpected response from server. Status : " + statusLine); } return Integer.parseInt(parts[1]); }
while ((b = inputStream.read()) != -1 && b != '\n') {
private static int readStatusCode(InputStream inputStream) throws IOException { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1 && b != '\n') { byteOutputStream.write(b); } String statusLine = byteOutputStream.toString("UTF-8").trim(); if (statusLine.isEmpty()) { inputStream.close(); throw new ProtocolException("Unexpected response from server."); } String[] parts = statusLine.split(" "); if (parts.length < 2) { inputStream.close(); throw new ProtocolException(("Unexpected response from server. Status : " + statusLine)); } return Integer.parseInt(parts[1]); }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { contentLength = -1; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param bufferedInputStream the input stream from the socket * @param outputStream the output stream from the socket for writing the request * @return an instance of Response */ private static Response<?> sendPatchRequest(HttpRequest httpRequest, BufferedInputStream bufferedInputStream, OutputStream outputStream) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); OutputStreamWriter out = new OutputStreamWriter(outputStream); buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, bufferedInputStream); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { UrlBuilder urlBuilder = UrlBuilder.parse(httpRequest.getUrl()) .setPath(redirectLocation); httpRequest.setUrl(urlBuilder.toUrl()); } return sendPatchRequest(httpRequest, bufferedInputStream, outputStream); } return response; } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * Response * * @param httpRequest The HTTP Request being sent * @param inputStream the input stream from the socket * @return an instance of Response * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedInputStream inputStream) throws IOException { int statusCode = readStatusCode(inputStream); HttpHeaders headers = readResponseHeaders(inputStream); HttpHeader contentLengthHeader = headers.get(CONTENT_LENGTH); byte[] body = getBody(inputStream, contentLengthHeader); if (body != null) { return new HttpResponse<>(httpRequest, statusCode, headers, BinaryData.fromBytes(body)); } return new HttpResponse<>(httpRequest, statusCode, headers, null); } private static byte[] getBody(BufferedInputStream inputStream, HttpHeader contentLengthHeader) throws IOException { int contentLength; if (contentLengthHeader == null || contentLengthHeader.getValue() == null) { return null; } else { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (contentLength > 0) { byte[] buffer = new byte[contentLength]; int bytesRead; int totalBytesRead = 0; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer, totalBytesRead, contentLength - totalBytesRead)) != -1) { totalBytesRead += bytesRead; } if (totalBytesRead != contentLength) { try { inputStream.close(); } catch (IOException e) { } throw new IOException("Read " + totalBytesRead + " bytes but expected " + contentLength); } return buffer; } return null; } private static HttpHeaders readResponseHeaders(InputStream inputStream) throws IOException { HttpHeaders headers = new HttpHeaders(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); int b; while ((b = inputStream.read()) != -1) { if (b == '\n') { String headerLine = byteOutputStream.toString("UTF-8").trim(); if (headerLine.isEmpty()) { return headers; } int split = headerLine.indexOf(':'); String key = headerLine.substring(0, split); String value = headerLine.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); byteOutputStream.reset(); } byteOutputStream.write(b); } return headers; } }
Why is this commented out?
public void testPoolOData() throws Exception { CloudPool pool = batchClient.poolOperations().getPool(poolId, new DetailLevel.Builder().withExpandClause("stats").build()); List<CloudPool> pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withSelectClause("id, state").build()); Assert.assertTrue(pools.size() > 0); Assert.assertNotNull(pools.get(0).id()); Assert.assertNull(pools.get(0).vmSize()); pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withFilterClause("state eq 'deleting'").build()); }
public void testPoolOData() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testPoolOData"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); try { List<CloudPool> pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withSelectClause("id, state").build()); Assert.assertTrue(pools.size() > 0); Assert.assertNotNull(pools.get(0).id()); Assert.assertNull(pools.get(0).vmSize()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } }
class PoolTests extends BatchIntegrationTestBase { private static CloudPool livePool; private static String poolId; private static NetworkConfiguration networkConfiguration; @BeforeClass public static void setup() throws Exception { poolId = getStringIdWithUserNamePrefix("-testpool"); if(isRecordMode()) { createClient(AuthMode.AAD); livePool = createIfNotExistIaaSPool(poolId); Assert.assertNotNull(livePool); } networkConfiguration = createNetworkConfiguration(); } @AfterClass public static void cleanup() throws Exception { try { } catch (Exception e) { } } @Test @Test public void canCRUDLowPriIaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-canCRUDLowPri-testPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.DEFAULT, pool.targetNodeCommunicationMode()); Assert.assertTrue(pool.networkConfiguration().enableAcceleratedNetworking()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); List<InboundEndpoint> inboundEndpoints = computeNodes.get(0).endpointConfiguration().inboundEndpoints(); Assert.assertEquals(2, inboundEndpoints.size()); InboundEndpoint inboundEndpoint = inboundEndpoints.get(0); Assert.assertEquals(5000, inboundEndpoint.backendPort()); Assert.assertTrue(inboundEndpoint.frontendPort() >= 60000); Assert.assertTrue(inboundEndpoint.frontendPort() <= 60040); Assert.assertTrue(inboundEndpoint.name().startsWith("testinbound.")); Assert.assertTrue(inboundEndpoints.get(1).name().startsWith("SSHRule")); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, poolNodeCount.lowPriority().total()); Assert.assertEquals(POOL_VM_COUNT, poolNodeCount.dedicated().total()); PoolUpdatePropertiesParameter updatePropertiesParam = new PoolUpdatePropertiesParameter(); updatePropertiesParam.withTargetNodeCommunicationMode(NodeCommunicationMode.SIMPLIFIED) .withApplicationPackageReferences( new LinkedList<ApplicationPackageReference>()) .withMetadata(new LinkedList<MetadataItem>()) .withCertificateReferences(new LinkedList<CertificateReference>()); batchClient.poolOperations().updatePoolProperties(poolId, updatePropertiesParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.SIMPLIFIED, pool.targetNodeCommunicationMode()); PoolPatchParameter patchParam = new PoolPatchParameter(); patchParam.withTargetNodeCommunicationMode(NodeCommunicationMode.CLASSIC); batchClient.poolOperations().patchPool(poolId, patchParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.CLASSIC, pool.targetNodeCommunicationMode()); batchClient.poolOperations().resizePool(poolId, 1, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(1, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canInstallVMExtension() throws Exception { String poolId = getStringIdWithUserNamePrefix("-installVMExtension"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 1; String VM_EXTENSION_NAME = "secretext"; String VM_EXTENSION_TYPE = "KeyVaultForLinux"; String VM_EXTENSION_PUBLISHER = "Microsoft.Azure.KeyVault"; String VM_TYPEHANDLER_VERSION = "1.0"; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; List<VMExtension> vmExtensions = new ArrayList<VMExtension>(); vmExtensions.add(new VMExtension().withName(VM_EXTENSION_NAME).withType(VM_EXTENSION_TYPE).withPublisher(VM_EXTENSION_PUBLISHER).withTypeHandlerVersion(VM_TYPEHANDLER_VERSION).withEnableAutomaticUpgrade(true)); ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef).withExtensions(vmExtensions); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); try{ long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); for(ComputeNode node : computeNodes){ NodeVMExtension nodeVMExtension = batchClient.protocolLayer().computeNodeExtensions().get(poolId, node.id(), VM_EXTENSION_NAME); Assert.assertNotNull(nodeVMExtension); Assert.assertTrue(nodeVMExtension.vmExtension().enableAutomaticUpgrade()); } boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); }finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateContainerPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)){ List<String> images = new ArrayList<String>(); images.add("tensorflow/tensorflow:latest-gpu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("microsoft-azure-batch").withOffer("ubuntu-server-container").withSku("20-04-lts")) .withNodeAgentSKUId("batch.node.ubuntu 20.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter addParameter = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(ContainerType.DOCKER_COMPATIBLE,pool.virtualMachineConfiguration().containerConfiguration().type()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateDataDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool3"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; int lun = 50; int diskSizeGB = 50; List<DataDisk> dataDisks = new ArrayList<DataDisk>(); dataDisks.add(new DataDisk().withLun(lun).withDiskSizeGB(diskSizeGB)); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04").withDataDisks(dataDisks); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withNetworkConfiguration(networkConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(configuration); try { batchClient.poolOperations().createPool(poolConfig); CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(lun, pool.virtualMachineConfiguration().dataDisks().get(0).lun()); Assert.assertEquals(diskSizeGB, pool.virtualMachineConfiguration().dataDisks().get(0).diskSizeGB()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateCustomImageWithExpectedError() throws Exception { String poolId = getStringIdWithUserNamePrefix("-customImageExpErr"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withImageReference(new ImageReference().withVirtualMachineImageId(String.format( "/subscriptions/%s/resourceGroups/batchexp/providers/Microsoft.Compute/images/FakeImage", System.getenv("SUBSCRIPTION_ID")))) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("Expect exception, but not got it."); } catch (BatchErrorException err) { if (err.body().code().equals("InsufficientPermissions")) { Assert.assertTrue(err.body().values().get(0).value().contains( "The user identity used for this operation does not have the required privilege Microsoft.Compute/images/read on the specified resource")); } else { if (!err.body().code().equals("InvalidPropertyValue")) { throw err; } } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateContainerPoolWithRegularImage() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerRegImage"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The specified imageReference with publisher Canonical offer UbuntuServer sku 18.04-LTS does not support container feature.", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateLinuxPoolWithWindowsConfig() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createLinuxPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("16.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); UserAccount windowsUser = new UserAccount(); windowsUser.withWindowsUserConfiguration(new WindowsUserConfiguration().withLoginMode(LoginMode.INTERACTIVE)) .withName("testaccount") .withPassword("password"); ArrayList<UserAccount> users = new ArrayList<UserAccount>(); users.add(windowsUser); PoolAddParameter pool = new PoolAddParameter().withId(poolId) .withVirtualMachineConfiguration(configuration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(0) .withVmSize(POOL_VM_SIZE) .withUserAccounts(users) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(pool); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The user configuration for user account 'testaccount' has a mismatch with the OS (Windows/Linux) configuration specified in VirtualMachineConfiguration", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCRUDLowPriPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool4"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 10 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); batchClient.poolOperations().createPool(new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT)); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); batchClient.poolOperations().resizePool(poolId, null, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(POOL_VM_COUNT, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } private static CloudPool waitForPoolState(String poolId, AllocationState targetState, long poolAllocationTimeoutInMilliseconds) throws IOException, InterruptedException { long startTime = System.currentTimeMillis(); long elapsedTime = 0L; boolean allocationStateReached = false; CloudPool pool = null; while (elapsedTime < poolAllocationTimeoutInMilliseconds) { pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); if (pool.allocationState() == targetState) { allocationStateReached = true; break; } System.out.println("wait 30 seconds for pool allocationStateReached..."); threadSleepInRecordMode(30 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue("The pool did not reach a allocationStateReached state in the allotted time", allocationStateReached); return pool; } @Test public void canCRUDPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-CRUDPaaS"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 3; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); List<UserAccount> userList = new ArrayList<>(); userList.add(new UserAccount().withName("test-user-1").withPassword("kt userList.add(new UserAccount().withName("test-user-2").withPassword("kt .withElevationLevel(ElevationLevel.ADMIN)); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withUserAccounts(userList); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertNotNull(pool.userAccounts()); Assert.assertEquals("test-user-1", pool.userAccounts().get(0).name()); Assert.assertEquals(ElevationLevel.NON_ADMIN, pool.userAccounts().get(0).elevationLevel()); Assert.assertNull(pool.userAccounts().get(0).password()); Assert.assertEquals(ElevationLevel.ADMIN, pool.userAccounts().get(1).elevationLevel()); List<CloudPool> pools = batchClient.poolOperations().listPools(); Assert.assertTrue(pools.size() > 0); boolean found = false; for (CloudPool p : pools) { if (p.id().equals(poolId)) { found = true; break; } } Assert.assertTrue(found); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(0, poolNodeCount.lowPriority().total()); Assert.assertEquals(3, poolNodeCount.dedicated().total()); LinkedList<MetadataItem> metadata = new LinkedList<>(); metadata.add((new MetadataItem()).withName("key1").withValue("value1")); batchClient.poolOperations().patchPool(poolId, null, null, null, metadata); pool = batchClient.poolOperations().getPool(poolId); Assert.assertTrue(pool.metadata().size() == 1); Assert.assertTrue(pool.metadata().get(0).name().equals("key1")); batchClient.poolOperations().updatePoolProperties(poolId, null, new LinkedList<CertificateReference>(), new LinkedList<ApplicationPackageReference>(), new LinkedList<MetadataItem>()); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNull(pool.metadata()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 5 seconds for pool delete..."); threadSleepInRecordMode(5 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithAutoOSUpgradeAndRollingUpgrade() throws Exception { String poolId = getStringIdWithUserNamePrefix("-autoOSUpgradeRollingUpgrade"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("UbuntuServer") .withSku("18.04-LTS"); NodePlacementConfiguration nodePlacementConfiguration = new NodePlacementConfiguration() .withPolicy(NodePlacementPolicyType.ZONAL); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withNodePlacementConfiguration(nodePlacementConfiguration); UpgradePolicy upgradePolicy = new UpgradePolicy() .withMode(UpgradeMode.AUTOMATIC) .withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy() .withDisableAutomaticRollback(true) .withEnableAutomaticOSUpgrade(true) .withUseRollingUpgradePolicy(true) .withOsRollingUpgradeDeferral(true)) .withRollingUpgradePolicy(new RollingUpgradePolicy() .withEnableCrossZoneUpgrade(true) .withMaxBatchInstancePercent(20) .withMaxUnhealthyInstancePercent(20) .withMaxUnhealthyUpgradedInstancePercent(20) .withPauseTimeBetweenBatches("PT5S") .withPrioritizeUnhealthyInstances(false) .withRollbackFailedInstancesOnPolicyBreach(false)); PoolAddParameter testPoolWithUpgradePolicy = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withUpgradePolicy(upgradePolicy); batchClient.poolOperations().createPool(testPoolWithUpgradePolicy); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); Assert.assertEquals("automatic", pool.upgradePolicy().mode().toString()); Assert.assertTrue(pool.upgradePolicy().automaticOSUpgradePolicy().enableAutomaticOSUpgrade()); Assert.assertTrue(pool.upgradePolicy().rollingUpgradePolicy().enableCrossZoneUpgrade()); Assert.assertEquals(20, (int) pool.upgradePolicy().rollingUpgradePolicy().maxBatchInstancePercent()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithSecurityProfileAndOSDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("SecurityProfile"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("0001-com-ubuntu-server-jammy") .withSku("22_04-lts"); SecurityProfile securityProfile = new SecurityProfile() .withSecurityType(SecurityTypes.TRUSTED_LAUNCH) .withEncryptionAtHost(true) .withUefiSettings(new UefiSettings() .withSecureBootEnabled(true) .withVTpmEnabled(true)); ManagedDisk managedDisk = new ManagedDisk() .withStorageAccountType(StorageAccountType.STANDARD_LRS); OSDisk osDisk = new OSDisk() .withCaching(CachingType.READ_WRITE) .withManagedDisk(managedDisk) .withDiskSizeGB(50) .withWriteAcceleratorEnabled(true); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 22.04") .withSecurityProfile(securityProfile) .withOsDisk(osDisk); PoolAddParameter poolAddParameter = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(0); batchClient.poolOperations().createPool(poolAddParameter); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); SecurityProfile sp = pool.virtualMachineConfiguration().securityProfile(); Assert.assertEquals(SecurityTypes.TRUSTED_LAUNCH, sp.securityType()); Assert.assertTrue(sp.encryptionAtHost()); Assert.assertTrue(sp.uefiSettings().secureBootEnabled()); Assert.assertTrue(sp.uefiSettings().vTpmEnabled()); OSDisk disk = pool.virtualMachineConfiguration().osDisk(); Assert.assertEquals("readwrite", pool.virtualMachineConfiguration().osDisk().caching().toString().toLowerCase()); Assert.assertEquals(StorageAccountType.STANDARD_LRS, disk.managedDisk().storageAccountType()); Assert.assertEquals(Integer.valueOf(50), disk.diskSizeGB()); Assert.assertTrue(disk.writeAcceleratorEnabled()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } }
class PoolTests extends BatchIntegrationTestBase { private static NetworkConfiguration networkConfiguration; @BeforeClass public static void setup() throws Exception { if(isRecordMode()) { createClient(AuthMode.AAD); } networkConfiguration = createNetworkConfiguration(); } @Test @Test public void canCRUDLowPriIaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-canCRUDLowPri-testPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.DEFAULT, pool.targetNodeCommunicationMode()); Assert.assertTrue(pool.networkConfiguration().enableAcceleratedNetworking()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); List<InboundEndpoint> inboundEndpoints = computeNodes.get(0).endpointConfiguration().inboundEndpoints(); Assert.assertEquals(2, inboundEndpoints.size()); InboundEndpoint inboundEndpoint = inboundEndpoints.get(0); Assert.assertEquals(5000, inboundEndpoint.backendPort()); Assert.assertTrue(inboundEndpoint.frontendPort() >= 60000); Assert.assertTrue(inboundEndpoint.frontendPort() <= 60040); Assert.assertTrue(inboundEndpoint.name().startsWith("testinbound.")); Assert.assertTrue(inboundEndpoints.get(1).name().startsWith("SSHRule")); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, poolNodeCount.lowPriority().total()); Assert.assertEquals(POOL_VM_COUNT, poolNodeCount.dedicated().total()); PoolUpdatePropertiesParameter updatePropertiesParam = new PoolUpdatePropertiesParameter(); updatePropertiesParam.withTargetNodeCommunicationMode(NodeCommunicationMode.SIMPLIFIED) .withApplicationPackageReferences( new LinkedList<ApplicationPackageReference>()) .withMetadata(new LinkedList<MetadataItem>()) .withCertificateReferences(new LinkedList<CertificateReference>()); batchClient.poolOperations().updatePoolProperties(poolId, updatePropertiesParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.SIMPLIFIED, pool.targetNodeCommunicationMode()); PoolPatchParameter patchParam = new PoolPatchParameter(); patchParam.withTargetNodeCommunicationMode(NodeCommunicationMode.CLASSIC); batchClient.poolOperations().patchPool(poolId, patchParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.CLASSIC, pool.targetNodeCommunicationMode()); batchClient.poolOperations().resizePool(poolId, 1, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(1, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canInstallVMExtension() throws Exception { String poolId = getStringIdWithUserNamePrefix("-installVMExtension"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 1; String VM_EXTENSION_NAME = "secretext"; String VM_EXTENSION_TYPE = "KeyVaultForLinux"; String VM_EXTENSION_PUBLISHER = "Microsoft.Azure.KeyVault"; String VM_TYPEHANDLER_VERSION = "1.0"; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; List<VMExtension> vmExtensions = new ArrayList<VMExtension>(); vmExtensions.add(new VMExtension().withName(VM_EXTENSION_NAME).withType(VM_EXTENSION_TYPE).withPublisher(VM_EXTENSION_PUBLISHER).withTypeHandlerVersion(VM_TYPEHANDLER_VERSION).withEnableAutomaticUpgrade(true)); ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef).withExtensions(vmExtensions); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); try{ long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); for(ComputeNode node : computeNodes){ NodeVMExtension nodeVMExtension = batchClient.protocolLayer().computeNodeExtensions().get(poolId, node.id(), VM_EXTENSION_NAME); Assert.assertNotNull(nodeVMExtension); Assert.assertTrue(nodeVMExtension.vmExtension().enableAutomaticUpgrade()); } boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); }finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateContainerPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)){ List<String> images = new ArrayList<String>(); images.add("tensorflow/tensorflow:latest-gpu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("microsoft-azure-batch").withOffer("ubuntu-server-container").withSku("20-04-lts")) .withNodeAgentSKUId("batch.node.ubuntu 20.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter addParameter = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(ContainerType.DOCKER_COMPATIBLE,pool.virtualMachineConfiguration().containerConfiguration().type()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateDataDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool3"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; int lun = 50; int diskSizeGB = 50; List<DataDisk> dataDisks = new ArrayList<DataDisk>(); dataDisks.add(new DataDisk().withLun(lun).withDiskSizeGB(diskSizeGB)); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04").withDataDisks(dataDisks); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withNetworkConfiguration(networkConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(configuration); try { batchClient.poolOperations().createPool(poolConfig); CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(lun, pool.virtualMachineConfiguration().dataDisks().get(0).lun()); Assert.assertEquals(diskSizeGB, pool.virtualMachineConfiguration().dataDisks().get(0).diskSizeGB()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateCustomImageWithExpectedError() throws Exception { String poolId = getStringIdWithUserNamePrefix("-customImageExpErr"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withImageReference(new ImageReference().withVirtualMachineImageId(String.format( "/subscriptions/%s/resourceGroups/batchexp/providers/Microsoft.Compute/images/FakeImage", System.getenv("SUBSCRIPTION_ID")))) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("Expect exception, but not got it."); } catch (BatchErrorException err) { if (err.body().code().equals("InsufficientPermissions")) { Assert.assertTrue(err.body().values().get(0).value().contains( "The user identity used for this operation does not have the required privilege Microsoft.Compute/images/read on the specified resource")); } else { if (!err.body().code().equals("InvalidPropertyValue")) { throw err; } } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateContainerPoolWithRegularImage() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerRegImage"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The specified imageReference with publisher Canonical offer UbuntuServer sku 18.04-LTS does not support container feature.", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateLinuxPoolWithWindowsConfig() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createLinuxPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("16.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); UserAccount windowsUser = new UserAccount(); windowsUser.withWindowsUserConfiguration(new WindowsUserConfiguration().withLoginMode(LoginMode.INTERACTIVE)) .withName("testaccount") .withPassword("password"); ArrayList<UserAccount> users = new ArrayList<UserAccount>(); users.add(windowsUser); PoolAddParameter pool = new PoolAddParameter().withId(poolId) .withVirtualMachineConfiguration(configuration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(0) .withVmSize(POOL_VM_SIZE) .withUserAccounts(users) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(pool); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The user configuration for user account 'testaccount' has a mismatch with the OS (Windows/Linux) configuration specified in VirtualMachineConfiguration", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCRUDLowPriPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool4"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 10 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); batchClient.poolOperations().createPool(new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT)); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); batchClient.poolOperations().resizePool(poolId, null, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(POOL_VM_COUNT, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } private static CloudPool waitForPoolState(String poolId, AllocationState targetState, long poolAllocationTimeoutInMilliseconds) throws IOException, InterruptedException { long startTime = System.currentTimeMillis(); long elapsedTime = 0L; boolean allocationStateReached = false; CloudPool pool = null; while (elapsedTime < poolAllocationTimeoutInMilliseconds) { pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); if (pool.allocationState() == targetState) { allocationStateReached = true; break; } System.out.println("wait 30 seconds for pool allocationStateReached..."); threadSleepInRecordMode(30 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue("The pool did not reach a allocationStateReached state in the allotted time", allocationStateReached); return pool; } @Test public void canCRUDPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-CRUDPaaS"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 3; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); List<UserAccount> userList = new ArrayList<>(); userList.add(new UserAccount().withName("test-user-1").withPassword("kt userList.add(new UserAccount().withName("test-user-2").withPassword("kt .withElevationLevel(ElevationLevel.ADMIN)); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withUserAccounts(userList); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertNotNull(pool.userAccounts()); Assert.assertEquals("test-user-1", pool.userAccounts().get(0).name()); Assert.assertEquals(ElevationLevel.NON_ADMIN, pool.userAccounts().get(0).elevationLevel()); Assert.assertNull(pool.userAccounts().get(0).password()); Assert.assertEquals(ElevationLevel.ADMIN, pool.userAccounts().get(1).elevationLevel()); List<CloudPool> pools = batchClient.poolOperations().listPools(); Assert.assertTrue(pools.size() > 0); boolean found = false; for (CloudPool p : pools) { if (p.id().equals(poolId)) { found = true; break; } } Assert.assertTrue(found); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(0, poolNodeCount.lowPriority().total()); Assert.assertEquals(3, poolNodeCount.dedicated().total()); LinkedList<MetadataItem> metadata = new LinkedList<>(); metadata.add((new MetadataItem()).withName("key1").withValue("value1")); batchClient.poolOperations().patchPool(poolId, null, null, null, metadata); pool = batchClient.poolOperations().getPool(poolId); Assert.assertTrue(pool.metadata().size() == 1); Assert.assertTrue(pool.metadata().get(0).name().equals("key1")); batchClient.poolOperations().updatePoolProperties(poolId, null, new LinkedList<CertificateReference>(), new LinkedList<ApplicationPackageReference>(), new LinkedList<MetadataItem>()); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNull(pool.metadata()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 5 seconds for pool delete..."); threadSleepInRecordMode(5 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithAutoOSUpgradeAndRollingUpgrade() throws Exception { String poolId = getStringIdWithUserNamePrefix("-autoOSUpgradeRollingUpgrade"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("UbuntuServer") .withSku("18.04-LTS"); NodePlacementConfiguration nodePlacementConfiguration = new NodePlacementConfiguration() .withPolicy(NodePlacementPolicyType.ZONAL); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withNodePlacementConfiguration(nodePlacementConfiguration); UpgradePolicy upgradePolicy = new UpgradePolicy() .withMode(UpgradeMode.AUTOMATIC) .withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy() .withDisableAutomaticRollback(true) .withEnableAutomaticOSUpgrade(true) .withUseRollingUpgradePolicy(true) .withOsRollingUpgradeDeferral(true)) .withRollingUpgradePolicy(new RollingUpgradePolicy() .withEnableCrossZoneUpgrade(true) .withMaxBatchInstancePercent(20) .withMaxUnhealthyInstancePercent(20) .withMaxUnhealthyUpgradedInstancePercent(20) .withPauseTimeBetweenBatches("PT5S") .withPrioritizeUnhealthyInstances(false) .withRollbackFailedInstancesOnPolicyBreach(false)); PoolAddParameter testPoolWithUpgradePolicy = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withUpgradePolicy(upgradePolicy); batchClient.poolOperations().createPool(testPoolWithUpgradePolicy); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); Assert.assertEquals("automatic", pool.upgradePolicy().mode().toString()); Assert.assertTrue(pool.upgradePolicy().automaticOSUpgradePolicy().enableAutomaticOSUpgrade()); Assert.assertTrue(pool.upgradePolicy().rollingUpgradePolicy().enableCrossZoneUpgrade()); Assert.assertEquals(20, (int) pool.upgradePolicy().rollingUpgradePolicy().maxBatchInstancePercent()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithSecurityProfileAndOSDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("SecurityProfile"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("0001-com-ubuntu-server-jammy") .withSku("22_04-lts"); SecurityProfile securityProfile = new SecurityProfile() .withSecurityType(SecurityTypes.TRUSTED_LAUNCH) .withEncryptionAtHost(true) .withUefiSettings(new UefiSettings() .withSecureBootEnabled(true) .withVTpmEnabled(true)); ManagedDisk managedDisk = new ManagedDisk() .withStorageAccountType(StorageAccountType.STANDARD_LRS); OSDisk osDisk = new OSDisk() .withCaching(CachingType.READ_WRITE) .withManagedDisk(managedDisk) .withDiskSizeGB(50) .withWriteAcceleratorEnabled(true); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 22.04") .withSecurityProfile(securityProfile) .withOsDisk(osDisk); PoolAddParameter poolAddParameter = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(0); batchClient.poolOperations().createPool(poolAddParameter); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); SecurityProfile sp = pool.virtualMachineConfiguration().securityProfile(); Assert.assertEquals(SecurityTypes.TRUSTED_LAUNCH, sp.securityType()); Assert.assertTrue(sp.encryptionAtHost()); Assert.assertTrue(sp.uefiSettings().secureBootEnabled()); Assert.assertTrue(sp.uefiSettings().vTpmEnabled()); OSDisk disk = pool.virtualMachineConfiguration().osDisk(); Assert.assertEquals("readwrite", pool.virtualMachineConfiguration().osDisk().caching().toString().toLowerCase()); Assert.assertEquals(StorageAccountType.STANDARD_LRS, disk.managedDisk().storageAccountType()); Assert.assertEquals(Integer.valueOf(50), disk.diskSizeGB()); Assert.assertTrue(disk.writeAcceleratorEnabled()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } }
Basically this assertion checks that no more than 1 pool is in the deleting phase at a time. According to Nick, Track 1 Record Tests are run in parallel (unlike Track 2 tests, which are run in sequential order), so it's entirely possible for >1 pool to be in the deleting stage at a time. I commented this assertion out because it kept on erroring out and I couldn't get the tests to pass without doing that, and it doesn't really impact the functionality of the tests themselves (i.e. it looks like they still work correctly even if >1 pool is in 'deleting' at a time). Nick suggested that I could add a dummy pool in the test, immediately delete it and then check that `Assert.assertTrue(pools.size() >= 1)`. I'm open to any suggestion regarding refactoring it! This assertion doesn't seem to be failing due to the content of the new tests added, more likely because there are 2 new tests (and thus higher chances of >1 pool being stuck in deleting as there are now 11 active total Pool Tests). Let me know any ideas on how to handle this! I just can't seem to get it to work when running the Record Tests unfortunately
public void testPoolOData() throws Exception { CloudPool pool = batchClient.poolOperations().getPool(poolId, new DetailLevel.Builder().withExpandClause("stats").build()); List<CloudPool> pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withSelectClause("id, state").build()); Assert.assertTrue(pools.size() > 0); Assert.assertNotNull(pools.get(0).id()); Assert.assertNull(pools.get(0).vmSize()); pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withFilterClause("state eq 'deleting'").build()); }
public void testPoolOData() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testPoolOData"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); try { List<CloudPool> pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withSelectClause("id, state").build()); Assert.assertTrue(pools.size() > 0); Assert.assertNotNull(pools.get(0).id()); Assert.assertNull(pools.get(0).vmSize()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } }
class PoolTests extends BatchIntegrationTestBase { private static CloudPool livePool; private static String poolId; private static NetworkConfiguration networkConfiguration; @BeforeClass public static void setup() throws Exception { poolId = getStringIdWithUserNamePrefix("-testpool"); if(isRecordMode()) { createClient(AuthMode.AAD); livePool = createIfNotExistIaaSPool(poolId); Assert.assertNotNull(livePool); } networkConfiguration = createNetworkConfiguration(); } @AfterClass public static void cleanup() throws Exception { try { } catch (Exception e) { } } @Test @Test public void canCRUDLowPriIaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-canCRUDLowPri-testPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.DEFAULT, pool.targetNodeCommunicationMode()); Assert.assertTrue(pool.networkConfiguration().enableAcceleratedNetworking()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); List<InboundEndpoint> inboundEndpoints = computeNodes.get(0).endpointConfiguration().inboundEndpoints(); Assert.assertEquals(2, inboundEndpoints.size()); InboundEndpoint inboundEndpoint = inboundEndpoints.get(0); Assert.assertEquals(5000, inboundEndpoint.backendPort()); Assert.assertTrue(inboundEndpoint.frontendPort() >= 60000); Assert.assertTrue(inboundEndpoint.frontendPort() <= 60040); Assert.assertTrue(inboundEndpoint.name().startsWith("testinbound.")); Assert.assertTrue(inboundEndpoints.get(1).name().startsWith("SSHRule")); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, poolNodeCount.lowPriority().total()); Assert.assertEquals(POOL_VM_COUNT, poolNodeCount.dedicated().total()); PoolUpdatePropertiesParameter updatePropertiesParam = new PoolUpdatePropertiesParameter(); updatePropertiesParam.withTargetNodeCommunicationMode(NodeCommunicationMode.SIMPLIFIED) .withApplicationPackageReferences( new LinkedList<ApplicationPackageReference>()) .withMetadata(new LinkedList<MetadataItem>()) .withCertificateReferences(new LinkedList<CertificateReference>()); batchClient.poolOperations().updatePoolProperties(poolId, updatePropertiesParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.SIMPLIFIED, pool.targetNodeCommunicationMode()); PoolPatchParameter patchParam = new PoolPatchParameter(); patchParam.withTargetNodeCommunicationMode(NodeCommunicationMode.CLASSIC); batchClient.poolOperations().patchPool(poolId, patchParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.CLASSIC, pool.targetNodeCommunicationMode()); batchClient.poolOperations().resizePool(poolId, 1, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(1, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canInstallVMExtension() throws Exception { String poolId = getStringIdWithUserNamePrefix("-installVMExtension"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 1; String VM_EXTENSION_NAME = "secretext"; String VM_EXTENSION_TYPE = "KeyVaultForLinux"; String VM_EXTENSION_PUBLISHER = "Microsoft.Azure.KeyVault"; String VM_TYPEHANDLER_VERSION = "1.0"; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; List<VMExtension> vmExtensions = new ArrayList<VMExtension>(); vmExtensions.add(new VMExtension().withName(VM_EXTENSION_NAME).withType(VM_EXTENSION_TYPE).withPublisher(VM_EXTENSION_PUBLISHER).withTypeHandlerVersion(VM_TYPEHANDLER_VERSION).withEnableAutomaticUpgrade(true)); ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef).withExtensions(vmExtensions); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); try{ long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); for(ComputeNode node : computeNodes){ NodeVMExtension nodeVMExtension = batchClient.protocolLayer().computeNodeExtensions().get(poolId, node.id(), VM_EXTENSION_NAME); Assert.assertNotNull(nodeVMExtension); Assert.assertTrue(nodeVMExtension.vmExtension().enableAutomaticUpgrade()); } boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); }finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateContainerPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)){ List<String> images = new ArrayList<String>(); images.add("tensorflow/tensorflow:latest-gpu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("microsoft-azure-batch").withOffer("ubuntu-server-container").withSku("20-04-lts")) .withNodeAgentSKUId("batch.node.ubuntu 20.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter addParameter = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(ContainerType.DOCKER_COMPATIBLE,pool.virtualMachineConfiguration().containerConfiguration().type()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateDataDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool3"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; int lun = 50; int diskSizeGB = 50; List<DataDisk> dataDisks = new ArrayList<DataDisk>(); dataDisks.add(new DataDisk().withLun(lun).withDiskSizeGB(diskSizeGB)); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04").withDataDisks(dataDisks); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withNetworkConfiguration(networkConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(configuration); try { batchClient.poolOperations().createPool(poolConfig); CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(lun, pool.virtualMachineConfiguration().dataDisks().get(0).lun()); Assert.assertEquals(diskSizeGB, pool.virtualMachineConfiguration().dataDisks().get(0).diskSizeGB()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateCustomImageWithExpectedError() throws Exception { String poolId = getStringIdWithUserNamePrefix("-customImageExpErr"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withImageReference(new ImageReference().withVirtualMachineImageId(String.format( "/subscriptions/%s/resourceGroups/batchexp/providers/Microsoft.Compute/images/FakeImage", System.getenv("SUBSCRIPTION_ID")))) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("Expect exception, but not got it."); } catch (BatchErrorException err) { if (err.body().code().equals("InsufficientPermissions")) { Assert.assertTrue(err.body().values().get(0).value().contains( "The user identity used for this operation does not have the required privilege Microsoft.Compute/images/read on the specified resource")); } else { if (!err.body().code().equals("InvalidPropertyValue")) { throw err; } } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateContainerPoolWithRegularImage() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerRegImage"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The specified imageReference with publisher Canonical offer UbuntuServer sku 18.04-LTS does not support container feature.", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateLinuxPoolWithWindowsConfig() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createLinuxPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("16.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); UserAccount windowsUser = new UserAccount(); windowsUser.withWindowsUserConfiguration(new WindowsUserConfiguration().withLoginMode(LoginMode.INTERACTIVE)) .withName("testaccount") .withPassword("password"); ArrayList<UserAccount> users = new ArrayList<UserAccount>(); users.add(windowsUser); PoolAddParameter pool = new PoolAddParameter().withId(poolId) .withVirtualMachineConfiguration(configuration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(0) .withVmSize(POOL_VM_SIZE) .withUserAccounts(users) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(pool); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The user configuration for user account 'testaccount' has a mismatch with the OS (Windows/Linux) configuration specified in VirtualMachineConfiguration", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCRUDLowPriPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool4"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 10 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); batchClient.poolOperations().createPool(new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT)); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); batchClient.poolOperations().resizePool(poolId, null, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(POOL_VM_COUNT, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } private static CloudPool waitForPoolState(String poolId, AllocationState targetState, long poolAllocationTimeoutInMilliseconds) throws IOException, InterruptedException { long startTime = System.currentTimeMillis(); long elapsedTime = 0L; boolean allocationStateReached = false; CloudPool pool = null; while (elapsedTime < poolAllocationTimeoutInMilliseconds) { pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); if (pool.allocationState() == targetState) { allocationStateReached = true; break; } System.out.println("wait 30 seconds for pool allocationStateReached..."); threadSleepInRecordMode(30 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue("The pool did not reach a allocationStateReached state in the allotted time", allocationStateReached); return pool; } @Test public void canCRUDPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-CRUDPaaS"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 3; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); List<UserAccount> userList = new ArrayList<>(); userList.add(new UserAccount().withName("test-user-1").withPassword("kt userList.add(new UserAccount().withName("test-user-2").withPassword("kt .withElevationLevel(ElevationLevel.ADMIN)); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withUserAccounts(userList); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertNotNull(pool.userAccounts()); Assert.assertEquals("test-user-1", pool.userAccounts().get(0).name()); Assert.assertEquals(ElevationLevel.NON_ADMIN, pool.userAccounts().get(0).elevationLevel()); Assert.assertNull(pool.userAccounts().get(0).password()); Assert.assertEquals(ElevationLevel.ADMIN, pool.userAccounts().get(1).elevationLevel()); List<CloudPool> pools = batchClient.poolOperations().listPools(); Assert.assertTrue(pools.size() > 0); boolean found = false; for (CloudPool p : pools) { if (p.id().equals(poolId)) { found = true; break; } } Assert.assertTrue(found); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(0, poolNodeCount.lowPriority().total()); Assert.assertEquals(3, poolNodeCount.dedicated().total()); LinkedList<MetadataItem> metadata = new LinkedList<>(); metadata.add((new MetadataItem()).withName("key1").withValue("value1")); batchClient.poolOperations().patchPool(poolId, null, null, null, metadata); pool = batchClient.poolOperations().getPool(poolId); Assert.assertTrue(pool.metadata().size() == 1); Assert.assertTrue(pool.metadata().get(0).name().equals("key1")); batchClient.poolOperations().updatePoolProperties(poolId, null, new LinkedList<CertificateReference>(), new LinkedList<ApplicationPackageReference>(), new LinkedList<MetadataItem>()); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNull(pool.metadata()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 5 seconds for pool delete..."); threadSleepInRecordMode(5 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithAutoOSUpgradeAndRollingUpgrade() throws Exception { String poolId = getStringIdWithUserNamePrefix("-autoOSUpgradeRollingUpgrade"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("UbuntuServer") .withSku("18.04-LTS"); NodePlacementConfiguration nodePlacementConfiguration = new NodePlacementConfiguration() .withPolicy(NodePlacementPolicyType.ZONAL); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withNodePlacementConfiguration(nodePlacementConfiguration); UpgradePolicy upgradePolicy = new UpgradePolicy() .withMode(UpgradeMode.AUTOMATIC) .withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy() .withDisableAutomaticRollback(true) .withEnableAutomaticOSUpgrade(true) .withUseRollingUpgradePolicy(true) .withOsRollingUpgradeDeferral(true)) .withRollingUpgradePolicy(new RollingUpgradePolicy() .withEnableCrossZoneUpgrade(true) .withMaxBatchInstancePercent(20) .withMaxUnhealthyInstancePercent(20) .withMaxUnhealthyUpgradedInstancePercent(20) .withPauseTimeBetweenBatches("PT5S") .withPrioritizeUnhealthyInstances(false) .withRollbackFailedInstancesOnPolicyBreach(false)); PoolAddParameter testPoolWithUpgradePolicy = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withUpgradePolicy(upgradePolicy); batchClient.poolOperations().createPool(testPoolWithUpgradePolicy); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); Assert.assertEquals("automatic", pool.upgradePolicy().mode().toString()); Assert.assertTrue(pool.upgradePolicy().automaticOSUpgradePolicy().enableAutomaticOSUpgrade()); Assert.assertTrue(pool.upgradePolicy().rollingUpgradePolicy().enableCrossZoneUpgrade()); Assert.assertEquals(20, (int) pool.upgradePolicy().rollingUpgradePolicy().maxBatchInstancePercent()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithSecurityProfileAndOSDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("SecurityProfile"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("0001-com-ubuntu-server-jammy") .withSku("22_04-lts"); SecurityProfile securityProfile = new SecurityProfile() .withSecurityType(SecurityTypes.TRUSTED_LAUNCH) .withEncryptionAtHost(true) .withUefiSettings(new UefiSettings() .withSecureBootEnabled(true) .withVTpmEnabled(true)); ManagedDisk managedDisk = new ManagedDisk() .withStorageAccountType(StorageAccountType.STANDARD_LRS); OSDisk osDisk = new OSDisk() .withCaching(CachingType.READ_WRITE) .withManagedDisk(managedDisk) .withDiskSizeGB(50) .withWriteAcceleratorEnabled(true); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 22.04") .withSecurityProfile(securityProfile) .withOsDisk(osDisk); PoolAddParameter poolAddParameter = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(0); batchClient.poolOperations().createPool(poolAddParameter); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); SecurityProfile sp = pool.virtualMachineConfiguration().securityProfile(); Assert.assertEquals(SecurityTypes.TRUSTED_LAUNCH, sp.securityType()); Assert.assertTrue(sp.encryptionAtHost()); Assert.assertTrue(sp.uefiSettings().secureBootEnabled()); Assert.assertTrue(sp.uefiSettings().vTpmEnabled()); OSDisk disk = pool.virtualMachineConfiguration().osDisk(); Assert.assertEquals("readwrite", pool.virtualMachineConfiguration().osDisk().caching().toString().toLowerCase()); Assert.assertEquals(StorageAccountType.STANDARD_LRS, disk.managedDisk().storageAccountType()); Assert.assertEquals(Integer.valueOf(50), disk.diskSizeGB()); Assert.assertTrue(disk.writeAcceleratorEnabled()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } }
class PoolTests extends BatchIntegrationTestBase { private static NetworkConfiguration networkConfiguration; @BeforeClass public static void setup() throws Exception { if(isRecordMode()) { createClient(AuthMode.AAD); } networkConfiguration = createNetworkConfiguration(); } @Test @Test public void canCRUDLowPriIaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-canCRUDLowPri-testPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.DEFAULT, pool.targetNodeCommunicationMode()); Assert.assertTrue(pool.networkConfiguration().enableAcceleratedNetworking()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); List<InboundEndpoint> inboundEndpoints = computeNodes.get(0).endpointConfiguration().inboundEndpoints(); Assert.assertEquals(2, inboundEndpoints.size()); InboundEndpoint inboundEndpoint = inboundEndpoints.get(0); Assert.assertEquals(5000, inboundEndpoint.backendPort()); Assert.assertTrue(inboundEndpoint.frontendPort() >= 60000); Assert.assertTrue(inboundEndpoint.frontendPort() <= 60040); Assert.assertTrue(inboundEndpoint.name().startsWith("testinbound.")); Assert.assertTrue(inboundEndpoints.get(1).name().startsWith("SSHRule")); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, poolNodeCount.lowPriority().total()); Assert.assertEquals(POOL_VM_COUNT, poolNodeCount.dedicated().total()); PoolUpdatePropertiesParameter updatePropertiesParam = new PoolUpdatePropertiesParameter(); updatePropertiesParam.withTargetNodeCommunicationMode(NodeCommunicationMode.SIMPLIFIED) .withApplicationPackageReferences( new LinkedList<ApplicationPackageReference>()) .withMetadata(new LinkedList<MetadataItem>()) .withCertificateReferences(new LinkedList<CertificateReference>()); batchClient.poolOperations().updatePoolProperties(poolId, updatePropertiesParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.SIMPLIFIED, pool.targetNodeCommunicationMode()); PoolPatchParameter patchParam = new PoolPatchParameter(); patchParam.withTargetNodeCommunicationMode(NodeCommunicationMode.CLASSIC); batchClient.poolOperations().patchPool(poolId, patchParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.CLASSIC, pool.targetNodeCommunicationMode()); batchClient.poolOperations().resizePool(poolId, 1, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(1, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canInstallVMExtension() throws Exception { String poolId = getStringIdWithUserNamePrefix("-installVMExtension"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 1; String VM_EXTENSION_NAME = "secretext"; String VM_EXTENSION_TYPE = "KeyVaultForLinux"; String VM_EXTENSION_PUBLISHER = "Microsoft.Azure.KeyVault"; String VM_TYPEHANDLER_VERSION = "1.0"; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; List<VMExtension> vmExtensions = new ArrayList<VMExtension>(); vmExtensions.add(new VMExtension().withName(VM_EXTENSION_NAME).withType(VM_EXTENSION_TYPE).withPublisher(VM_EXTENSION_PUBLISHER).withTypeHandlerVersion(VM_TYPEHANDLER_VERSION).withEnableAutomaticUpgrade(true)); ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef).withExtensions(vmExtensions); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); try{ long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); for(ComputeNode node : computeNodes){ NodeVMExtension nodeVMExtension = batchClient.protocolLayer().computeNodeExtensions().get(poolId, node.id(), VM_EXTENSION_NAME); Assert.assertNotNull(nodeVMExtension); Assert.assertTrue(nodeVMExtension.vmExtension().enableAutomaticUpgrade()); } boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); }finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateContainerPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)){ List<String> images = new ArrayList<String>(); images.add("tensorflow/tensorflow:latest-gpu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("microsoft-azure-batch").withOffer("ubuntu-server-container").withSku("20-04-lts")) .withNodeAgentSKUId("batch.node.ubuntu 20.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter addParameter = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(ContainerType.DOCKER_COMPATIBLE,pool.virtualMachineConfiguration().containerConfiguration().type()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateDataDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool3"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; int lun = 50; int diskSizeGB = 50; List<DataDisk> dataDisks = new ArrayList<DataDisk>(); dataDisks.add(new DataDisk().withLun(lun).withDiskSizeGB(diskSizeGB)); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04").withDataDisks(dataDisks); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withNetworkConfiguration(networkConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(configuration); try { batchClient.poolOperations().createPool(poolConfig); CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(lun, pool.virtualMachineConfiguration().dataDisks().get(0).lun()); Assert.assertEquals(diskSizeGB, pool.virtualMachineConfiguration().dataDisks().get(0).diskSizeGB()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateCustomImageWithExpectedError() throws Exception { String poolId = getStringIdWithUserNamePrefix("-customImageExpErr"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withImageReference(new ImageReference().withVirtualMachineImageId(String.format( "/subscriptions/%s/resourceGroups/batchexp/providers/Microsoft.Compute/images/FakeImage", System.getenv("SUBSCRIPTION_ID")))) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("Expect exception, but not got it."); } catch (BatchErrorException err) { if (err.body().code().equals("InsufficientPermissions")) { Assert.assertTrue(err.body().values().get(0).value().contains( "The user identity used for this operation does not have the required privilege Microsoft.Compute/images/read on the specified resource")); } else { if (!err.body().code().equals("InvalidPropertyValue")) { throw err; } } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateContainerPoolWithRegularImage() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerRegImage"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The specified imageReference with publisher Canonical offer UbuntuServer sku 18.04-LTS does not support container feature.", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateLinuxPoolWithWindowsConfig() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createLinuxPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("16.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); UserAccount windowsUser = new UserAccount(); windowsUser.withWindowsUserConfiguration(new WindowsUserConfiguration().withLoginMode(LoginMode.INTERACTIVE)) .withName("testaccount") .withPassword("password"); ArrayList<UserAccount> users = new ArrayList<UserAccount>(); users.add(windowsUser); PoolAddParameter pool = new PoolAddParameter().withId(poolId) .withVirtualMachineConfiguration(configuration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(0) .withVmSize(POOL_VM_SIZE) .withUserAccounts(users) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(pool); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The user configuration for user account 'testaccount' has a mismatch with the OS (Windows/Linux) configuration specified in VirtualMachineConfiguration", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCRUDLowPriPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool4"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 10 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); batchClient.poolOperations().createPool(new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT)); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); batchClient.poolOperations().resizePool(poolId, null, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(POOL_VM_COUNT, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } private static CloudPool waitForPoolState(String poolId, AllocationState targetState, long poolAllocationTimeoutInMilliseconds) throws IOException, InterruptedException { long startTime = System.currentTimeMillis(); long elapsedTime = 0L; boolean allocationStateReached = false; CloudPool pool = null; while (elapsedTime < poolAllocationTimeoutInMilliseconds) { pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); if (pool.allocationState() == targetState) { allocationStateReached = true; break; } System.out.println("wait 30 seconds for pool allocationStateReached..."); threadSleepInRecordMode(30 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue("The pool did not reach a allocationStateReached state in the allotted time", allocationStateReached); return pool; } @Test public void canCRUDPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-CRUDPaaS"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 3; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); List<UserAccount> userList = new ArrayList<>(); userList.add(new UserAccount().withName("test-user-1").withPassword("kt userList.add(new UserAccount().withName("test-user-2").withPassword("kt .withElevationLevel(ElevationLevel.ADMIN)); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withUserAccounts(userList); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertNotNull(pool.userAccounts()); Assert.assertEquals("test-user-1", pool.userAccounts().get(0).name()); Assert.assertEquals(ElevationLevel.NON_ADMIN, pool.userAccounts().get(0).elevationLevel()); Assert.assertNull(pool.userAccounts().get(0).password()); Assert.assertEquals(ElevationLevel.ADMIN, pool.userAccounts().get(1).elevationLevel()); List<CloudPool> pools = batchClient.poolOperations().listPools(); Assert.assertTrue(pools.size() > 0); boolean found = false; for (CloudPool p : pools) { if (p.id().equals(poolId)) { found = true; break; } } Assert.assertTrue(found); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(0, poolNodeCount.lowPriority().total()); Assert.assertEquals(3, poolNodeCount.dedicated().total()); LinkedList<MetadataItem> metadata = new LinkedList<>(); metadata.add((new MetadataItem()).withName("key1").withValue("value1")); batchClient.poolOperations().patchPool(poolId, null, null, null, metadata); pool = batchClient.poolOperations().getPool(poolId); Assert.assertTrue(pool.metadata().size() == 1); Assert.assertTrue(pool.metadata().get(0).name().equals("key1")); batchClient.poolOperations().updatePoolProperties(poolId, null, new LinkedList<CertificateReference>(), new LinkedList<ApplicationPackageReference>(), new LinkedList<MetadataItem>()); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNull(pool.metadata()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 5 seconds for pool delete..."); threadSleepInRecordMode(5 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithAutoOSUpgradeAndRollingUpgrade() throws Exception { String poolId = getStringIdWithUserNamePrefix("-autoOSUpgradeRollingUpgrade"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("UbuntuServer") .withSku("18.04-LTS"); NodePlacementConfiguration nodePlacementConfiguration = new NodePlacementConfiguration() .withPolicy(NodePlacementPolicyType.ZONAL); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withNodePlacementConfiguration(nodePlacementConfiguration); UpgradePolicy upgradePolicy = new UpgradePolicy() .withMode(UpgradeMode.AUTOMATIC) .withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy() .withDisableAutomaticRollback(true) .withEnableAutomaticOSUpgrade(true) .withUseRollingUpgradePolicy(true) .withOsRollingUpgradeDeferral(true)) .withRollingUpgradePolicy(new RollingUpgradePolicy() .withEnableCrossZoneUpgrade(true) .withMaxBatchInstancePercent(20) .withMaxUnhealthyInstancePercent(20) .withMaxUnhealthyUpgradedInstancePercent(20) .withPauseTimeBetweenBatches("PT5S") .withPrioritizeUnhealthyInstances(false) .withRollbackFailedInstancesOnPolicyBreach(false)); PoolAddParameter testPoolWithUpgradePolicy = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withUpgradePolicy(upgradePolicy); batchClient.poolOperations().createPool(testPoolWithUpgradePolicy); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); Assert.assertEquals("automatic", pool.upgradePolicy().mode().toString()); Assert.assertTrue(pool.upgradePolicy().automaticOSUpgradePolicy().enableAutomaticOSUpgrade()); Assert.assertTrue(pool.upgradePolicy().rollingUpgradePolicy().enableCrossZoneUpgrade()); Assert.assertEquals(20, (int) pool.upgradePolicy().rollingUpgradePolicy().maxBatchInstancePercent()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithSecurityProfileAndOSDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("SecurityProfile"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("0001-com-ubuntu-server-jammy") .withSku("22_04-lts"); SecurityProfile securityProfile = new SecurityProfile() .withSecurityType(SecurityTypes.TRUSTED_LAUNCH) .withEncryptionAtHost(true) .withUefiSettings(new UefiSettings() .withSecureBootEnabled(true) .withVTpmEnabled(true)); ManagedDisk managedDisk = new ManagedDisk() .withStorageAccountType(StorageAccountType.STANDARD_LRS); OSDisk osDisk = new OSDisk() .withCaching(CachingType.READ_WRITE) .withManagedDisk(managedDisk) .withDiskSizeGB(50) .withWriteAcceleratorEnabled(true); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 22.04") .withSecurityProfile(securityProfile) .withOsDisk(osDisk); PoolAddParameter poolAddParameter = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(0); batchClient.poolOperations().createPool(poolAddParameter); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); SecurityProfile sp = pool.virtualMachineConfiguration().securityProfile(); Assert.assertEquals(SecurityTypes.TRUSTED_LAUNCH, sp.securityType()); Assert.assertTrue(sp.encryptionAtHost()); Assert.assertTrue(sp.uefiSettings().secureBootEnabled()); Assert.assertTrue(sp.uefiSettings().vTpmEnabled()); OSDisk disk = pool.virtualMachineConfiguration().osDisk(); Assert.assertEquals("readwrite", pool.virtualMachineConfiguration().osDisk().caching().toString().toLowerCase()); Assert.assertEquals(StorageAccountType.STANDARD_LRS, disk.managedDisk().storageAccountType()); Assert.assertEquals(Integer.valueOf(50), disk.diskSizeGB()); Assert.assertTrue(disk.writeAcceleratorEnabled()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } }
Yeah, this test is flaky the way it's written, but we also can't just comment out the assertion since that defeats the purpose of the test. Looking through this file, it looks like we're already creating and deleting a pool for every other test. Can we get rid of the `@BeforeClass` and `@AfterClass` functions? I don't see why we have a static variable livePool at all. If we then create a pool inside `testPoolOData`, we can just assert that the expected pool exists in the list. Then there's no issue with other test pools existing. As far as I can see this won't affect test performance at all, because we'd be removing one pool create call and adding one.
public void testPoolOData() throws Exception { CloudPool pool = batchClient.poolOperations().getPool(poolId, new DetailLevel.Builder().withExpandClause("stats").build()); List<CloudPool> pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withSelectClause("id, state").build()); Assert.assertTrue(pools.size() > 0); Assert.assertNotNull(pools.get(0).id()); Assert.assertNull(pools.get(0).vmSize()); pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withFilterClause("state eq 'deleting'").build()); }
public void testPoolOData() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testPoolOData"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); try { List<CloudPool> pools = batchClient.poolOperations() .listPools(new DetailLevel.Builder().withSelectClause("id, state").build()); Assert.assertTrue(pools.size() > 0); Assert.assertNotNull(pools.get(0).id()); Assert.assertNull(pools.get(0).vmSize()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } }
class PoolTests extends BatchIntegrationTestBase { private static CloudPool livePool; private static String poolId; private static NetworkConfiguration networkConfiguration; @BeforeClass public static void setup() throws Exception { poolId = getStringIdWithUserNamePrefix("-testpool"); if(isRecordMode()) { createClient(AuthMode.AAD); livePool = createIfNotExistIaaSPool(poolId); Assert.assertNotNull(livePool); } networkConfiguration = createNetworkConfiguration(); } @AfterClass public static void cleanup() throws Exception { try { } catch (Exception e) { } } @Test @Test public void canCRUDLowPriIaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-canCRUDLowPri-testPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.DEFAULT, pool.targetNodeCommunicationMode()); Assert.assertTrue(pool.networkConfiguration().enableAcceleratedNetworking()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); List<InboundEndpoint> inboundEndpoints = computeNodes.get(0).endpointConfiguration().inboundEndpoints(); Assert.assertEquals(2, inboundEndpoints.size()); InboundEndpoint inboundEndpoint = inboundEndpoints.get(0); Assert.assertEquals(5000, inboundEndpoint.backendPort()); Assert.assertTrue(inboundEndpoint.frontendPort() >= 60000); Assert.assertTrue(inboundEndpoint.frontendPort() <= 60040); Assert.assertTrue(inboundEndpoint.name().startsWith("testinbound.")); Assert.assertTrue(inboundEndpoints.get(1).name().startsWith("SSHRule")); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, poolNodeCount.lowPriority().total()); Assert.assertEquals(POOL_VM_COUNT, poolNodeCount.dedicated().total()); PoolUpdatePropertiesParameter updatePropertiesParam = new PoolUpdatePropertiesParameter(); updatePropertiesParam.withTargetNodeCommunicationMode(NodeCommunicationMode.SIMPLIFIED) .withApplicationPackageReferences( new LinkedList<ApplicationPackageReference>()) .withMetadata(new LinkedList<MetadataItem>()) .withCertificateReferences(new LinkedList<CertificateReference>()); batchClient.poolOperations().updatePoolProperties(poolId, updatePropertiesParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.SIMPLIFIED, pool.targetNodeCommunicationMode()); PoolPatchParameter patchParam = new PoolPatchParameter(); patchParam.withTargetNodeCommunicationMode(NodeCommunicationMode.CLASSIC); batchClient.poolOperations().patchPool(poolId, patchParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.CLASSIC, pool.targetNodeCommunicationMode()); batchClient.poolOperations().resizePool(poolId, 1, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(1, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canInstallVMExtension() throws Exception { String poolId = getStringIdWithUserNamePrefix("-installVMExtension"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 1; String VM_EXTENSION_NAME = "secretext"; String VM_EXTENSION_TYPE = "KeyVaultForLinux"; String VM_EXTENSION_PUBLISHER = "Microsoft.Azure.KeyVault"; String VM_TYPEHANDLER_VERSION = "1.0"; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; List<VMExtension> vmExtensions = new ArrayList<VMExtension>(); vmExtensions.add(new VMExtension().withName(VM_EXTENSION_NAME).withType(VM_EXTENSION_TYPE).withPublisher(VM_EXTENSION_PUBLISHER).withTypeHandlerVersion(VM_TYPEHANDLER_VERSION).withEnableAutomaticUpgrade(true)); ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef).withExtensions(vmExtensions); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); try{ long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); for(ComputeNode node : computeNodes){ NodeVMExtension nodeVMExtension = batchClient.protocolLayer().computeNodeExtensions().get(poolId, node.id(), VM_EXTENSION_NAME); Assert.assertNotNull(nodeVMExtension); Assert.assertTrue(nodeVMExtension.vmExtension().enableAutomaticUpgrade()); } boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); }finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateContainerPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)){ List<String> images = new ArrayList<String>(); images.add("tensorflow/tensorflow:latest-gpu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("microsoft-azure-batch").withOffer("ubuntu-server-container").withSku("20-04-lts")) .withNodeAgentSKUId("batch.node.ubuntu 20.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter addParameter = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(ContainerType.DOCKER_COMPATIBLE,pool.virtualMachineConfiguration().containerConfiguration().type()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateDataDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool3"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; int lun = 50; int diskSizeGB = 50; List<DataDisk> dataDisks = new ArrayList<DataDisk>(); dataDisks.add(new DataDisk().withLun(lun).withDiskSizeGB(diskSizeGB)); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04").withDataDisks(dataDisks); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withNetworkConfiguration(networkConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(configuration); try { batchClient.poolOperations().createPool(poolConfig); CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(lun, pool.virtualMachineConfiguration().dataDisks().get(0).lun()); Assert.assertEquals(diskSizeGB, pool.virtualMachineConfiguration().dataDisks().get(0).diskSizeGB()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateCustomImageWithExpectedError() throws Exception { String poolId = getStringIdWithUserNamePrefix("-customImageExpErr"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withImageReference(new ImageReference().withVirtualMachineImageId(String.format( "/subscriptions/%s/resourceGroups/batchexp/providers/Microsoft.Compute/images/FakeImage", System.getenv("SUBSCRIPTION_ID")))) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("Expect exception, but not got it."); } catch (BatchErrorException err) { if (err.body().code().equals("InsufficientPermissions")) { Assert.assertTrue(err.body().values().get(0).value().contains( "The user identity used for this operation does not have the required privilege Microsoft.Compute/images/read on the specified resource")); } else { if (!err.body().code().equals("InvalidPropertyValue")) { throw err; } } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateContainerPoolWithRegularImage() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerRegImage"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The specified imageReference with publisher Canonical offer UbuntuServer sku 18.04-LTS does not support container feature.", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateLinuxPoolWithWindowsConfig() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createLinuxPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("16.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); UserAccount windowsUser = new UserAccount(); windowsUser.withWindowsUserConfiguration(new WindowsUserConfiguration().withLoginMode(LoginMode.INTERACTIVE)) .withName("testaccount") .withPassword("password"); ArrayList<UserAccount> users = new ArrayList<UserAccount>(); users.add(windowsUser); PoolAddParameter pool = new PoolAddParameter().withId(poolId) .withVirtualMachineConfiguration(configuration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(0) .withVmSize(POOL_VM_SIZE) .withUserAccounts(users) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(pool); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The user configuration for user account 'testaccount' has a mismatch with the OS (Windows/Linux) configuration specified in VirtualMachineConfiguration", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCRUDLowPriPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool4"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 10 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); batchClient.poolOperations().createPool(new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT)); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); batchClient.poolOperations().resizePool(poolId, null, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(POOL_VM_COUNT, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } private static CloudPool waitForPoolState(String poolId, AllocationState targetState, long poolAllocationTimeoutInMilliseconds) throws IOException, InterruptedException { long startTime = System.currentTimeMillis(); long elapsedTime = 0L; boolean allocationStateReached = false; CloudPool pool = null; while (elapsedTime < poolAllocationTimeoutInMilliseconds) { pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); if (pool.allocationState() == targetState) { allocationStateReached = true; break; } System.out.println("wait 30 seconds for pool allocationStateReached..."); threadSleepInRecordMode(30 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue("The pool did not reach a allocationStateReached state in the allotted time", allocationStateReached); return pool; } @Test public void canCRUDPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-CRUDPaaS"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 3; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); List<UserAccount> userList = new ArrayList<>(); userList.add(new UserAccount().withName("test-user-1").withPassword("kt userList.add(new UserAccount().withName("test-user-2").withPassword("kt .withElevationLevel(ElevationLevel.ADMIN)); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withUserAccounts(userList); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertNotNull(pool.userAccounts()); Assert.assertEquals("test-user-1", pool.userAccounts().get(0).name()); Assert.assertEquals(ElevationLevel.NON_ADMIN, pool.userAccounts().get(0).elevationLevel()); Assert.assertNull(pool.userAccounts().get(0).password()); Assert.assertEquals(ElevationLevel.ADMIN, pool.userAccounts().get(1).elevationLevel()); List<CloudPool> pools = batchClient.poolOperations().listPools(); Assert.assertTrue(pools.size() > 0); boolean found = false; for (CloudPool p : pools) { if (p.id().equals(poolId)) { found = true; break; } } Assert.assertTrue(found); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(0, poolNodeCount.lowPriority().total()); Assert.assertEquals(3, poolNodeCount.dedicated().total()); LinkedList<MetadataItem> metadata = new LinkedList<>(); metadata.add((new MetadataItem()).withName("key1").withValue("value1")); batchClient.poolOperations().patchPool(poolId, null, null, null, metadata); pool = batchClient.poolOperations().getPool(poolId); Assert.assertTrue(pool.metadata().size() == 1); Assert.assertTrue(pool.metadata().get(0).name().equals("key1")); batchClient.poolOperations().updatePoolProperties(poolId, null, new LinkedList<CertificateReference>(), new LinkedList<ApplicationPackageReference>(), new LinkedList<MetadataItem>()); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNull(pool.metadata()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 5 seconds for pool delete..."); threadSleepInRecordMode(5 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithAutoOSUpgradeAndRollingUpgrade() throws Exception { String poolId = getStringIdWithUserNamePrefix("-autoOSUpgradeRollingUpgrade"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("UbuntuServer") .withSku("18.04-LTS"); NodePlacementConfiguration nodePlacementConfiguration = new NodePlacementConfiguration() .withPolicy(NodePlacementPolicyType.ZONAL); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withNodePlacementConfiguration(nodePlacementConfiguration); UpgradePolicy upgradePolicy = new UpgradePolicy() .withMode(UpgradeMode.AUTOMATIC) .withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy() .withDisableAutomaticRollback(true) .withEnableAutomaticOSUpgrade(true) .withUseRollingUpgradePolicy(true) .withOsRollingUpgradeDeferral(true)) .withRollingUpgradePolicy(new RollingUpgradePolicy() .withEnableCrossZoneUpgrade(true) .withMaxBatchInstancePercent(20) .withMaxUnhealthyInstancePercent(20) .withMaxUnhealthyUpgradedInstancePercent(20) .withPauseTimeBetweenBatches("PT5S") .withPrioritizeUnhealthyInstances(false) .withRollbackFailedInstancesOnPolicyBreach(false)); PoolAddParameter testPoolWithUpgradePolicy = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withUpgradePolicy(upgradePolicy); batchClient.poolOperations().createPool(testPoolWithUpgradePolicy); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); Assert.assertEquals("automatic", pool.upgradePolicy().mode().toString()); Assert.assertTrue(pool.upgradePolicy().automaticOSUpgradePolicy().enableAutomaticOSUpgrade()); Assert.assertTrue(pool.upgradePolicy().rollingUpgradePolicy().enableCrossZoneUpgrade()); Assert.assertEquals(20, (int) pool.upgradePolicy().rollingUpgradePolicy().maxBatchInstancePercent()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithSecurityProfileAndOSDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("SecurityProfile"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("0001-com-ubuntu-server-jammy") .withSku("22_04-lts"); SecurityProfile securityProfile = new SecurityProfile() .withSecurityType(SecurityTypes.TRUSTED_LAUNCH) .withEncryptionAtHost(true) .withUefiSettings(new UefiSettings() .withSecureBootEnabled(true) .withVTpmEnabled(true)); ManagedDisk managedDisk = new ManagedDisk() .withStorageAccountType(StorageAccountType.STANDARD_LRS); OSDisk osDisk = new OSDisk() .withCaching(CachingType.READ_WRITE) .withManagedDisk(managedDisk) .withDiskSizeGB(50) .withWriteAcceleratorEnabled(true); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 22.04") .withSecurityProfile(securityProfile) .withOsDisk(osDisk); PoolAddParameter poolAddParameter = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(0); batchClient.poolOperations().createPool(poolAddParameter); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); SecurityProfile sp = pool.virtualMachineConfiguration().securityProfile(); Assert.assertEquals(SecurityTypes.TRUSTED_LAUNCH, sp.securityType()); Assert.assertTrue(sp.encryptionAtHost()); Assert.assertTrue(sp.uefiSettings().secureBootEnabled()); Assert.assertTrue(sp.uefiSettings().vTpmEnabled()); OSDisk disk = pool.virtualMachineConfiguration().osDisk(); Assert.assertEquals("readwrite", pool.virtualMachineConfiguration().osDisk().caching().toString().toLowerCase()); Assert.assertEquals(StorageAccountType.STANDARD_LRS, disk.managedDisk().storageAccountType()); Assert.assertEquals(Integer.valueOf(50), disk.diskSizeGB()); Assert.assertTrue(disk.writeAcceleratorEnabled()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } }
class PoolTests extends BatchIntegrationTestBase { private static NetworkConfiguration networkConfiguration; @BeforeClass public static void setup() throws Exception { if(isRecordMode()) { createClient(AuthMode.AAD); } networkConfiguration = createNetworkConfiguration(); } @Test @Test public void canCRUDLowPriIaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-canCRUDLowPri-testPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 2; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef); NetworkConfiguration netConfig = createNetworkConfiguration(); PoolEndpointConfiguration endpointConfig = new PoolEndpointConfiguration(); List<InboundNATPool> inbounds = new ArrayList<>(); inbounds.add(new InboundNATPool().withName("testinbound").withProtocol(InboundEndpointProtocol.TCP) .withBackendPort(5000).withFrontendPortRangeStart(60000).withFrontendPortRangeEnd(60040)); endpointConfig.withInboundNATPools(inbounds); netConfig.withEndpointConfiguration(endpointConfig).withEnableAcceleratedNetworking(true); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(netConfig) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.DEFAULT, pool.targetNodeCommunicationMode()); Assert.assertTrue(pool.networkConfiguration().enableAcceleratedNetworking()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); List<InboundEndpoint> inboundEndpoints = computeNodes.get(0).endpointConfiguration().inboundEndpoints(); Assert.assertEquals(2, inboundEndpoints.size()); InboundEndpoint inboundEndpoint = inboundEndpoints.get(0); Assert.assertEquals(5000, inboundEndpoint.backendPort()); Assert.assertTrue(inboundEndpoint.frontendPort() >= 60000); Assert.assertTrue(inboundEndpoint.frontendPort() <= 60040); Assert.assertTrue(inboundEndpoint.name().startsWith("testinbound.")); Assert.assertTrue(inboundEndpoints.get(1).name().startsWith("SSHRule")); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, poolNodeCount.lowPriority().total()); Assert.assertEquals(POOL_VM_COUNT, poolNodeCount.dedicated().total()); PoolUpdatePropertiesParameter updatePropertiesParam = new PoolUpdatePropertiesParameter(); updatePropertiesParam.withTargetNodeCommunicationMode(NodeCommunicationMode.SIMPLIFIED) .withApplicationPackageReferences( new LinkedList<ApplicationPackageReference>()) .withMetadata(new LinkedList<MetadataItem>()) .withCertificateReferences(new LinkedList<CertificateReference>()); batchClient.poolOperations().updatePoolProperties(poolId, updatePropertiesParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.SIMPLIFIED, pool.targetNodeCommunicationMode()); PoolPatchParameter patchParam = new PoolPatchParameter(); patchParam.withTargetNodeCommunicationMode(NodeCommunicationMode.CLASSIC); batchClient.poolOperations().patchPool(poolId, patchParam); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull("CurrentNodeCommunicationMode should be defined for pool with more than one target dedicated node", pool.currentNodeCommunicationMode()); Assert.assertEquals(NodeCommunicationMode.CLASSIC, pool.targetNodeCommunicationMode()); batchClient.poolOperations().resizePool(poolId, 1, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(1, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canInstallVMExtension() throws Exception { String poolId = getStringIdWithUserNamePrefix("-installVMExtension"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 1; String VM_EXTENSION_NAME = "secretext"; String VM_EXTENSION_TYPE = "KeyVaultForLinux"; String VM_EXTENSION_PUBLISHER = "Microsoft.Azure.KeyVault"; String VM_TYPEHANDLER_VERSION = "1.0"; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; List<VMExtension> vmExtensions = new ArrayList<VMExtension>(); vmExtensions.add(new VMExtension().withName(VM_EXTENSION_NAME).withType(VM_EXTENSION_TYPE).withPublisher(VM_EXTENSION_PUBLISHER).withTypeHandlerVersion(VM_TYPEHANDLER_VERSION).withEnableAutomaticUpgrade(true)); ImageReference imgRef = new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer") .withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withNodeAgentSKUId("batch.node.ubuntu 18.04").withImageReference(imgRef).withExtensions(vmExtensions); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withTargetDedicatedNodes(POOL_VM_COUNT).withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT) .withVmSize(POOL_VM_SIZE).withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration) .withTargetNodeCommunicationMode(NodeCommunicationMode.DEFAULT); batchClient.poolOperations().createPool(addParameter); try{ long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); List<ComputeNode> computeNodes = batchClient.computeNodeOperations().listComputeNodes(poolId); for(ComputeNode node : computeNodes){ NodeVMExtension nodeVMExtension = batchClient.protocolLayer().computeNodeExtensions().get(poolId, node.id(), VM_EXTENSION_NAME); Assert.assertNotNull(nodeVMExtension); Assert.assertTrue(nodeVMExtension.vmExtension().enableAutomaticUpgrade()); } boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); }finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateContainerPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; long POOL_STEADY_TIMEOUT_IN_MILLISECONDS = 10 * 60 * 1000; TimeUnit.SECONDS.toMillis(30); if (!batchClient.poolOperations().existsPool(poolId)){ List<String> images = new ArrayList<String>(); images.add("tensorflow/tensorflow:latest-gpu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("microsoft-azure-batch").withOffer("ubuntu-server-container").withSku("20-04-lts")) .withNodeAgentSKUId("batch.node.ubuntu 20.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter addParameter = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_MILLISECONDS); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(ContainerType.DOCKER_COMPATIBLE,pool.virtualMachineConfiguration().containerConfiguration().type()); boolean deleted = false; elapsedTime = 0L; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_MILLISECONDS) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateDataDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool3"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; int lun = 50; int diskSizeGB = 50; List<DataDisk> dataDisks = new ArrayList<DataDisk>(); dataDisks.add(new DataDisk().withLun(lun).withDiskSizeGB(diskSizeGB)); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04").withDataDisks(dataDisks); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withNetworkConfiguration(networkConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(configuration); try { batchClient.poolOperations().createPool(poolConfig); CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(lun, pool.virtualMachineConfiguration().dataDisks().get(0).lun()); Assert.assertEquals(diskSizeGB, pool.virtualMachineConfiguration().dataDisks().get(0).diskSizeGB()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCreateCustomImageWithExpectedError() throws Exception { String poolId = getStringIdWithUserNamePrefix("-customImageExpErr"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration.withImageReference(new ImageReference().withVirtualMachineImageId(String.format( "/subscriptions/%s/resourceGroups/batchexp/providers/Microsoft.Compute/images/FakeImage", System.getenv("SUBSCRIPTION_ID")))) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("Expect exception, but not got it."); } catch (BatchErrorException err) { if (err.body().code().equals("InsufficientPermissions")) { Assert.assertTrue(err.body().values().get(0).value().contains( "The user identity used for this operation does not have the required privilege Microsoft.Compute/images/read on the specified resource")); } else { if (!err.body().code().equals("InvalidPropertyValue")) { throw err; } } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateContainerPoolWithRegularImage() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createContainerRegImage"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("18.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withContainerConfiguration(new ContainerConfiguration().withContainerImageNames(images).withType(ContainerType.DOCKER_COMPATIBLE)); PoolAddParameter poolConfig = new PoolAddParameter() .withId(poolId) .withVmSize(POOL_VM_SIZE) .withTargetDedicatedNodes(POOL_VM_COUNT) .withVirtualMachineConfiguration(configuration) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(poolConfig); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The specified imageReference with publisher Canonical offer UbuntuServer sku 18.04-LTS does not support container feature.", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void shouldFailOnCreateLinuxPoolWithWindowsConfig() throws Exception { String poolId = getStringIdWithUserNamePrefix("-createLinuxPool"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 0; List<String> images = new ArrayList<String>(); images.add("ubuntu"); VirtualMachineConfiguration configuration = new VirtualMachineConfiguration(); configuration .withImageReference( new ImageReference().withPublisher("Canonical").withOffer("UbuntuServer").withSku("16.04-LTS")) .withNodeAgentSKUId("batch.node.ubuntu 16.04"); UserAccount windowsUser = new UserAccount(); windowsUser.withWindowsUserConfiguration(new WindowsUserConfiguration().withLoginMode(LoginMode.INTERACTIVE)) .withName("testaccount") .withPassword("password"); ArrayList<UserAccount> users = new ArrayList<UserAccount>(); users.add(windowsUser); PoolAddParameter pool = new PoolAddParameter().withId(poolId) .withVirtualMachineConfiguration(configuration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(0) .withVmSize(POOL_VM_SIZE) .withUserAccounts(users) .withNetworkConfiguration(networkConfiguration); try { batchClient.poolOperations().createPool(pool); throw new Exception("The test case should throw exception here"); } catch (BatchErrorException err) { if (err.body().code().equals("InvalidPropertyValue")) { for (int i = 0; i < err.body().values().size(); i++) { if (err.body().values().get(i).key().equals("Reason")) { Assert.assertEquals( "The user configuration for user account 'testaccount' has a mismatch with the OS (Windows/Linux) configuration specified in VirtualMachineConfiguration", err.body().values().get(i).value()); return; } } throw new Exception("Couldn't find expect error reason"); } else { throw err; } } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void canCRUDLowPriPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-testpool4"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 1; int POOL_LOW_PRI_VM_COUNT = 2; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 10 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); batchClient.poolOperations().createPool(new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withTargetLowPriorityNodes(POOL_LOW_PRI_VM_COUNT)); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertEquals(POOL_VM_COUNT, (long) pool.currentDedicatedNodes()); Assert.assertEquals(POOL_LOW_PRI_VM_COUNT, (long) pool.currentLowPriorityNodes()); batchClient.poolOperations().resizePool(poolId, null, 1); pool = batchClient.poolOperations().getPool(poolId); Assert.assertEquals(POOL_VM_COUNT, (long) pool.targetDedicatedNodes()); Assert.assertEquals(1, (long) pool.targetLowPriorityNodes()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds * 2) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 15 seconds for pool delete..."); threadSleepInRecordMode(15 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } private static CloudPool waitForPoolState(String poolId, AllocationState targetState, long poolAllocationTimeoutInMilliseconds) throws IOException, InterruptedException { long startTime = System.currentTimeMillis(); long elapsedTime = 0L; boolean allocationStateReached = false; CloudPool pool = null; while (elapsedTime < poolAllocationTimeoutInMilliseconds) { pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); if (pool.allocationState() == targetState) { allocationStateReached = true; break; } System.out.println("wait 30 seconds for pool allocationStateReached..."); threadSleepInRecordMode(30 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue("The pool did not reach a allocationStateReached state in the allotted time", allocationStateReached); return pool; } @Test public void canCRUDPaaSPool() throws Exception { String poolId = getStringIdWithUserNamePrefix("-CRUDPaaS"); String POOL_VM_SIZE = "STANDARD_D1_V2"; int POOL_VM_COUNT = 3; long POOL_STEADY_TIMEOUT_IN_Milliseconds = 15 * 60 * 1000; if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference().withPublisher("Canonical") .withOffer("UbuntuServer").withSku("18.04-LTS").withVersion("latest"); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference).withNodeAgentSKUId("batch.node.ubuntu 18.04"); List<UserAccount> userList = new ArrayList<>(); userList.add(new UserAccount().withName("test-user-1").withPassword("kt userList.add(new UserAccount().withName("test-user-2").withPassword("kt .withElevationLevel(ElevationLevel.ADMIN)); PoolAddParameter addParameter = new PoolAddParameter().withId(poolId) .withVmSize(POOL_VM_SIZE) .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(POOL_VM_COUNT) .withUserAccounts(userList); batchClient.poolOperations().createPool(addParameter); } try { Assert.assertTrue(batchClient.poolOperations().existsPool(poolId)); long startTime = System.currentTimeMillis(); long elapsedTime = 0L; CloudPool pool = waitForPoolState(poolId, AllocationState.STEADY, POOL_STEADY_TIMEOUT_IN_Milliseconds); Assert.assertNotNull(pool.userAccounts()); Assert.assertEquals("test-user-1", pool.userAccounts().get(0).name()); Assert.assertEquals(ElevationLevel.NON_ADMIN, pool.userAccounts().get(0).elevationLevel()); Assert.assertNull(pool.userAccounts().get(0).password()); Assert.assertEquals(ElevationLevel.ADMIN, pool.userAccounts().get(1).elevationLevel()); List<CloudPool> pools = batchClient.poolOperations().listPools(); Assert.assertTrue(pools.size() > 0); boolean found = false; for (CloudPool p : pools) { if (p.id().equals(poolId)) { found = true; break; } } Assert.assertTrue(found); PoolNodeCounts poolNodeCount = null; List<PoolNodeCounts> poolNodeCounts = batchClient.accountOperations().listPoolNodeCounts(); for (PoolNodeCounts tmp : poolNodeCounts) { if (tmp.poolId().equals(poolId)) { poolNodeCount = tmp; break; } } Assert.assertNotNull(poolNodeCount); Assert.assertNotNull(poolNodeCount.lowPriority()); Assert.assertEquals(0, poolNodeCount.lowPriority().total()); Assert.assertEquals(3, poolNodeCount.dedicated().total()); LinkedList<MetadataItem> metadata = new LinkedList<>(); metadata.add((new MetadataItem()).withName("key1").withValue("value1")); batchClient.poolOperations().patchPool(poolId, null, null, null, metadata); pool = batchClient.poolOperations().getPool(poolId); Assert.assertTrue(pool.metadata().size() == 1); Assert.assertTrue(pool.metadata().get(0).name().equals("key1")); batchClient.poolOperations().updatePoolProperties(poolId, null, new LinkedList<CertificateReference>(), new LinkedList<ApplicationPackageReference>(), new LinkedList<MetadataItem>()); pool = batchClient.poolOperations().getPool(poolId); Assert.assertNull(pool.metadata()); boolean deleted = false; batchClient.poolOperations().deletePool(poolId); while (elapsedTime < POOL_STEADY_TIMEOUT_IN_Milliseconds) { try { batchClient.poolOperations().getPool(poolId); } catch (BatchErrorException err) { if (err.body().code().equals(BatchErrorCodeStrings.PoolNotFound)) { deleted = true; break; } else { throw err; } } System.out.println("wait 5 seconds for pool delete..."); threadSleepInRecordMode(5 * 1000); elapsedTime = (new Date()).getTime() - startTime; } Assert.assertTrue(deleted); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithAutoOSUpgradeAndRollingUpgrade() throws Exception { String poolId = getStringIdWithUserNamePrefix("-autoOSUpgradeRollingUpgrade"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("UbuntuServer") .withSku("18.04-LTS"); NodePlacementConfiguration nodePlacementConfiguration = new NodePlacementConfiguration() .withPolicy(NodePlacementPolicyType.ZONAL); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 18.04") .withNodePlacementConfiguration(nodePlacementConfiguration); UpgradePolicy upgradePolicy = new UpgradePolicy() .withMode(UpgradeMode.AUTOMATIC) .withAutomaticOSUpgradePolicy(new AutomaticOSUpgradePolicy() .withDisableAutomaticRollback(true) .withEnableAutomaticOSUpgrade(true) .withUseRollingUpgradePolicy(true) .withOsRollingUpgradeDeferral(true)) .withRollingUpgradePolicy(new RollingUpgradePolicy() .withEnableCrossZoneUpgrade(true) .withMaxBatchInstancePercent(20) .withMaxUnhealthyInstancePercent(20) .withMaxUnhealthyUpgradedInstancePercent(20) .withPauseTimeBetweenBatches("PT5S") .withPrioritizeUnhealthyInstances(false) .withRollbackFailedInstancesOnPolicyBreach(false)); PoolAddParameter testPoolWithUpgradePolicy = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withUpgradePolicy(upgradePolicy); batchClient.poolOperations().createPool(testPoolWithUpgradePolicy); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); Assert.assertEquals("automatic", pool.upgradePolicy().mode().toString()); Assert.assertTrue(pool.upgradePolicy().automaticOSUpgradePolicy().enableAutomaticOSUpgrade()); Assert.assertTrue(pool.upgradePolicy().rollingUpgradePolicy().enableCrossZoneUpgrade()); Assert.assertEquals(20, (int) pool.upgradePolicy().rollingUpgradePolicy().maxBatchInstancePercent()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } @Test public void testPoolWithSecurityProfileAndOSDisk() throws Exception { String poolId = getStringIdWithUserNamePrefix("SecurityProfile"); if (!batchClient.poolOperations().existsPool(poolId)) { ImageReference imageReference = new ImageReference() .withPublisher("Canonical") .withOffer("0001-com-ubuntu-server-jammy") .withSku("22_04-lts"); SecurityProfile securityProfile = new SecurityProfile() .withSecurityType(SecurityTypes.TRUSTED_LAUNCH) .withEncryptionAtHost(true) .withUefiSettings(new UefiSettings() .withSecureBootEnabled(true) .withVTpmEnabled(true)); ManagedDisk managedDisk = new ManagedDisk() .withStorageAccountType(StorageAccountType.STANDARD_LRS); OSDisk osDisk = new OSDisk() .withCaching(CachingType.READ_WRITE) .withManagedDisk(managedDisk) .withDiskSizeGB(50) .withWriteAcceleratorEnabled(true); VirtualMachineConfiguration vmConfiguration = new VirtualMachineConfiguration() .withImageReference(imageReference) .withNodeAgentSKUId("batch.node.ubuntu 22.04") .withSecurityProfile(securityProfile) .withOsDisk(osDisk); PoolAddParameter poolAddParameter = new PoolAddParameter() .withId(poolId) .withVmSize("STANDARD_D2S_V3") .withVirtualMachineConfiguration(vmConfiguration) .withTargetDedicatedNodes(0); batchClient.poolOperations().createPool(poolAddParameter); } try { CloudPool pool = batchClient.poolOperations().getPool(poolId); Assert.assertNotNull(pool); SecurityProfile sp = pool.virtualMachineConfiguration().securityProfile(); Assert.assertEquals(SecurityTypes.TRUSTED_LAUNCH, sp.securityType()); Assert.assertTrue(sp.encryptionAtHost()); Assert.assertTrue(sp.uefiSettings().secureBootEnabled()); Assert.assertTrue(sp.uefiSettings().vTpmEnabled()); OSDisk disk = pool.virtualMachineConfiguration().osDisk(); Assert.assertEquals("readwrite", pool.virtualMachineConfiguration().osDisk().caching().toString().toLowerCase()); Assert.assertEquals(StorageAccountType.STANDARD_LRS, disk.managedDisk().storageAccountType()); Assert.assertEquals(Integer.valueOf(50), disk.diskSizeGB()); Assert.assertTrue(disk.writeAcceleratorEnabled()); } finally { try { if (batchClient.poolOperations().existsPool(poolId)) { batchClient.poolOperations().deletePool(poolId); } } catch (Exception e) { } } } }
Is this dropping the stack trace logging or just handling it elsewhere?
private static void zeroPad(int value, byte[] bytes, int index) { if (value < 10) { bytes[index++] = '0'; bytes[index] = (byte) ('0' + value); } else { int high = value / 10; bytes[index++] = (byte) ('0' + high); bytes[index] = (byte) ('0' + (value - (10 * high))); } }
} else {
private static void zeroPad(int value, byte[] bytes, int index) { if (value < 10) { bytes[index++] = '0'; bytes[index] = (byte) ('0' + value); } else { int high = value / 10; bytes[index++] = (byte) ('0' + high); bytes[index] = (byte) ('0' + (value - (10 * high))); } }
class name may not correlate to an actual class. return className; } } private static LogLevel fromEnvironment() { String level = EnvironmentConfiguration.getGlobalConfiguration().get(Configuration.PROPERTY_LOG_LEVEL); return LogLevel.fromString(level); }
class name may not correlate to an actual class. return className; } } private static LogLevel fromEnvironment() { String level = EnvironmentConfiguration.getGlobalConfiguration().get(Configuration.PROPERTY_LOG_LEVEL); return LogLevel.fromString(level); }
we add coresponding context props in ClientLogger - https://github.com/Azure/azure-sdk-for-java/blob/919e3da1f1bfdd0143db7441757ceccbae9d43f7/sdk/generic-sdk-core/generic-core/src/main/java/com/generic/core/util/ClientLogger.java#L490-L496 needed to simplify life, but also reliably add closing `}`. Arguably it's a bit less efficient, but if exception is throw it's already so bad for perf that resizing context list is super-minor.
private static void zeroPad(int value, byte[] bytes, int index) { if (value < 10) { bytes[index++] = '0'; bytes[index] = (byte) ('0' + value); } else { int high = value / 10; bytes[index++] = (byte) ('0' + high); bytes[index] = (byte) ('0' + (value - (10 * high))); } }
} else {
private static void zeroPad(int value, byte[] bytes, int index) { if (value < 10) { bytes[index++] = '0'; bytes[index] = (byte) ('0' + value); } else { int high = value / 10; bytes[index++] = (byte) ('0' + high); bytes[index] = (byte) ('0' + (value - (10 * high))); } }
class name may not correlate to an actual class. return className; } } private static LogLevel fromEnvironment() { String level = EnvironmentConfiguration.getGlobalConfiguration().get(Configuration.PROPERTY_LOG_LEVEL); return LogLevel.fromString(level); }
class name may not correlate to an actual class. return className; } } private static LogLevel fromEnvironment() { String level = EnvironmentConfiguration.getGlobalConfiguration().get(Configuration.PROPERTY_LOG_LEVEL); return LogLevel.fromString(level); }
what if getConsecutiveExceptionCountToleratedForReads() is 1? Does 2 need to be a config settting?
public int getAllowedExceptionCountToMaintainStatus(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } else { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites() / 2; case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } }
return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2;
public int getAllowedExceptionCountToMaintainStatus(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } else { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } }
class ConsecutiveExceptionBasedCircuitBreaker { private static final Logger logger = LoggerFactory.getLogger(ConsecutiveExceptionBasedCircuitBreaker.class); private final PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig; public ConsecutiveExceptionBasedCircuitBreaker(PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig) { this.partitionLevelCircuitBreakerConfig = partitionLevelCircuitBreakerConfig; } public LocationSpecificHealthContext handleException(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: case HealthyTentative: exceptionCountAfterHandling++; int successCountAfterHandling = 0; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case Unavailable: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } } public LocationSpecificHealthContext handleSuccess(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); int successCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: exceptionCountAfterHandling = 0; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case HealthyTentative: successCountAfterHandling++; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case Unavailable: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } } public boolean shouldHealthStatusBeDowngraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); return exceptionCountActual >= getAllowedExceptionCountToMaintainStatus(locationSpecificHealthContext.getLocationHealthStatus(), isReadOnlyRequest); } public boolean canHealthStatusBeUpgraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int successCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); return successCountActual >= getMinimumSuccessCountForStatusUpgrade(locationHealthStatus, isReadOnlyRequest); } public int getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } else { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } } public boolean isPartitionLevelCircuitBreakerEnabled() { return this.partitionLevelCircuitBreakerConfig.isPartitionLevelCircuitBreakerEnabled(); } public PartitionLevelCircuitBreakerConfig getPartitionLevelCircuitBreakerConfig() { return partitionLevelCircuitBreakerConfig; } }
class ConsecutiveExceptionBasedCircuitBreaker { private static final Logger logger = LoggerFactory.getLogger(ConsecutiveExceptionBasedCircuitBreaker.class); private final PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig; public ConsecutiveExceptionBasedCircuitBreaker(PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig) { this.partitionLevelCircuitBreakerConfig = partitionLevelCircuitBreakerConfig; } public LocationSpecificHealthContext handleException( LocationSpecificHealthContext locationSpecificHealthContext, PartitionKeyRangeWrapper partitionKeyRangeWrapper, String regionWithException, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: case HealthyTentative: exceptionCountAfterHandling++; int successCountAfterHandling = 0; LocationSpecificHealthContext.Builder builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case Unavailable: logger.warn("Region {} should not be handling failures in {} health status for partition key range : {} and collection RID : {}", regionWithException, locationHealthStatus.getStringifiedLocationHealthStatus(), partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive() + "-" + partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive(), partitionKeyRangeWrapper.getCollectionResourceId()); return locationSpecificHealthContext; default: throw new IllegalArgumentException("Unsupported health status : " + locationHealthStatus); } } public LocationSpecificHealthContext handleSuccess( LocationSpecificHealthContext locationSpecificHealthContext, PartitionKeyRangeWrapper partitionKeyRangeWrapper, String regionWithSuccess, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); int successCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: exceptionCountAfterHandling = 0; LocationSpecificHealthContext.Builder builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case HealthyTentative: successCountAfterHandling++; builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case Unavailable: logger.warn("Region {} should not be handling successes in {} health status for partition key range : {} and collection RID : {}", regionWithSuccess, locationHealthStatus.getStringifiedLocationHealthStatus(), partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive() + "-" + partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive(), partitionKeyRangeWrapper.getCollectionResourceId()); return locationSpecificHealthContext; default: throw new IllegalArgumentException("Unsupported health status : " + locationHealthStatus); } } public boolean shouldHealthStatusBeDowngraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); return exceptionCountActual >= getAllowedExceptionCountToMaintainStatus(locationSpecificHealthContext.getLocationHealthStatus(), isReadOnlyRequest); } public boolean canHealthStatusBeUpgraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int successCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); return successCountActual >= getMinimumSuccessCountForStatusUpgrade(locationHealthStatus, isReadOnlyRequest); } public int getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } else { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } } public boolean isPartitionLevelCircuitBreakerEnabled() { return this.partitionLevelCircuitBreakerConfig.isPartitionLevelCircuitBreakerEnabled(); } public PartitionLevelCircuitBreakerConfig getPartitionLevelCircuitBreakerConfig() { return partitionLevelCircuitBreakerConfig; } }
ditto below for writes
public int getAllowedExceptionCountToMaintainStatus(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } else { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites() / 2; case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } }
return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2;
public int getAllowedExceptionCountToMaintainStatus(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } else { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } }
class ConsecutiveExceptionBasedCircuitBreaker { private static final Logger logger = LoggerFactory.getLogger(ConsecutiveExceptionBasedCircuitBreaker.class); private final PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig; public ConsecutiveExceptionBasedCircuitBreaker(PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig) { this.partitionLevelCircuitBreakerConfig = partitionLevelCircuitBreakerConfig; } public LocationSpecificHealthContext handleException(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: case HealthyTentative: exceptionCountAfterHandling++; int successCountAfterHandling = 0; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case Unavailable: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } } public LocationSpecificHealthContext handleSuccess(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); int successCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: exceptionCountAfterHandling = 0; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case HealthyTentative: successCountAfterHandling++; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case Unavailable: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } } public boolean shouldHealthStatusBeDowngraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); return exceptionCountActual >= getAllowedExceptionCountToMaintainStatus(locationSpecificHealthContext.getLocationHealthStatus(), isReadOnlyRequest); } public boolean canHealthStatusBeUpgraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int successCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); return successCountActual >= getMinimumSuccessCountForStatusUpgrade(locationHealthStatus, isReadOnlyRequest); } public int getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } else { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } } public boolean isPartitionLevelCircuitBreakerEnabled() { return this.partitionLevelCircuitBreakerConfig.isPartitionLevelCircuitBreakerEnabled(); } public PartitionLevelCircuitBreakerConfig getPartitionLevelCircuitBreakerConfig() { return partitionLevelCircuitBreakerConfig; } }
class ConsecutiveExceptionBasedCircuitBreaker { private static final Logger logger = LoggerFactory.getLogger(ConsecutiveExceptionBasedCircuitBreaker.class); private final PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig; public ConsecutiveExceptionBasedCircuitBreaker(PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig) { this.partitionLevelCircuitBreakerConfig = partitionLevelCircuitBreakerConfig; } public LocationSpecificHealthContext handleException( LocationSpecificHealthContext locationSpecificHealthContext, PartitionKeyRangeWrapper partitionKeyRangeWrapper, String regionWithException, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: case HealthyTentative: exceptionCountAfterHandling++; int successCountAfterHandling = 0; LocationSpecificHealthContext.Builder builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case Unavailable: logger.warn("Region {} should not be handling failures in {} health status for partition key range : {} and collection RID : {}", regionWithException, locationHealthStatus.getStringifiedLocationHealthStatus(), partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive() + "-" + partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive(), partitionKeyRangeWrapper.getCollectionResourceId()); return locationSpecificHealthContext; default: throw new IllegalArgumentException("Unsupported health status : " + locationHealthStatus); } } public LocationSpecificHealthContext handleSuccess( LocationSpecificHealthContext locationSpecificHealthContext, PartitionKeyRangeWrapper partitionKeyRangeWrapper, String regionWithSuccess, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); int successCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: exceptionCountAfterHandling = 0; LocationSpecificHealthContext.Builder builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case HealthyTentative: successCountAfterHandling++; builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case Unavailable: logger.warn("Region {} should not be handling successes in {} health status for partition key range : {} and collection RID : {}", regionWithSuccess, locationHealthStatus.getStringifiedLocationHealthStatus(), partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive() + "-" + partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive(), partitionKeyRangeWrapper.getCollectionResourceId()); return locationSpecificHealthContext; default: throw new IllegalArgumentException("Unsupported health status : " + locationHealthStatus); } } public boolean shouldHealthStatusBeDowngraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); return exceptionCountActual >= getAllowedExceptionCountToMaintainStatus(locationSpecificHealthContext.getLocationHealthStatus(), isReadOnlyRequest); } public boolean canHealthStatusBeUpgraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int successCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); return successCountActual >= getMinimumSuccessCountForStatusUpgrade(locationHealthStatus, isReadOnlyRequest); } public int getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } else { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } } public boolean isPartitionLevelCircuitBreakerEnabled() { return this.partitionLevelCircuitBreakerConfig.isPartitionLevelCircuitBreakerEnabled(); } public PartitionLevelCircuitBreakerConfig getPartitionLevelCircuitBreakerConfig() { return partitionLevelCircuitBreakerConfig; } }
Worth discussing in our sync up on the guidance for this - idea was to make a partition health recovery conservative (twice as conservative here) but at the same time if exception count tolerated is 1 or 2 then we are failing over too quickly in the first place. This will increase latency due to cross-region calls and introduce behavior where we simply cycle through all regions as we keep failing over and back.
public int getAllowedExceptionCountToMaintainStatus(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } else { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites() / 2; case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } }
return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2;
public int getAllowedExceptionCountToMaintainStatus(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } else { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } }
class ConsecutiveExceptionBasedCircuitBreaker { private static final Logger logger = LoggerFactory.getLogger(ConsecutiveExceptionBasedCircuitBreaker.class); private final PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig; public ConsecutiveExceptionBasedCircuitBreaker(PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig) { this.partitionLevelCircuitBreakerConfig = partitionLevelCircuitBreakerConfig; } public LocationSpecificHealthContext handleException(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: case HealthyTentative: exceptionCountAfterHandling++; int successCountAfterHandling = 0; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case Unavailable: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } } public LocationSpecificHealthContext handleSuccess(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); int successCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: exceptionCountAfterHandling = 0; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case HealthyTentative: successCountAfterHandling++; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case Unavailable: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } } public boolean shouldHealthStatusBeDowngraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); return exceptionCountActual >= getAllowedExceptionCountToMaintainStatus(locationSpecificHealthContext.getLocationHealthStatus(), isReadOnlyRequest); } public boolean canHealthStatusBeUpgraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int successCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); return successCountActual >= getMinimumSuccessCountForStatusUpgrade(locationHealthStatus, isReadOnlyRequest); } public int getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } else { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } } public boolean isPartitionLevelCircuitBreakerEnabled() { return this.partitionLevelCircuitBreakerConfig.isPartitionLevelCircuitBreakerEnabled(); } public PartitionLevelCircuitBreakerConfig getPartitionLevelCircuitBreakerConfig() { return partitionLevelCircuitBreakerConfig; } }
class ConsecutiveExceptionBasedCircuitBreaker { private static final Logger logger = LoggerFactory.getLogger(ConsecutiveExceptionBasedCircuitBreaker.class); private final PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig; public ConsecutiveExceptionBasedCircuitBreaker(PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig) { this.partitionLevelCircuitBreakerConfig = partitionLevelCircuitBreakerConfig; } public LocationSpecificHealthContext handleException( LocationSpecificHealthContext locationSpecificHealthContext, PartitionKeyRangeWrapper partitionKeyRangeWrapper, String regionWithException, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: case HealthyTentative: exceptionCountAfterHandling++; int successCountAfterHandling = 0; LocationSpecificHealthContext.Builder builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case Unavailable: logger.warn("Region {} should not be handling failures in {} health status for partition key range : {} and collection RID : {}", regionWithException, locationHealthStatus.getStringifiedLocationHealthStatus(), partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive() + "-" + partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive(), partitionKeyRangeWrapper.getCollectionResourceId()); return locationSpecificHealthContext; default: throw new IllegalArgumentException("Unsupported health status : " + locationHealthStatus); } } public LocationSpecificHealthContext handleSuccess( LocationSpecificHealthContext locationSpecificHealthContext, PartitionKeyRangeWrapper partitionKeyRangeWrapper, String regionWithSuccess, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); int successCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: exceptionCountAfterHandling = 0; LocationSpecificHealthContext.Builder builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case HealthyTentative: successCountAfterHandling++; builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case Unavailable: logger.warn("Region {} should not be handling successes in {} health status for partition key range : {} and collection RID : {}", regionWithSuccess, locationHealthStatus.getStringifiedLocationHealthStatus(), partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive() + "-" + partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive(), partitionKeyRangeWrapper.getCollectionResourceId()); return locationSpecificHealthContext; default: throw new IllegalArgumentException("Unsupported health status : " + locationHealthStatus); } } public boolean shouldHealthStatusBeDowngraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); return exceptionCountActual >= getAllowedExceptionCountToMaintainStatus(locationSpecificHealthContext.getLocationHealthStatus(), isReadOnlyRequest); } public boolean canHealthStatusBeUpgraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int successCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); return successCountActual >= getMinimumSuccessCountForStatusUpgrade(locationHealthStatus, isReadOnlyRequest); } public int getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } else { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } } public boolean isPartitionLevelCircuitBreakerEnabled() { return this.partitionLevelCircuitBreakerConfig.isPartitionLevelCircuitBreakerEnabled(); } public PartitionLevelCircuitBreakerConfig getPartitionLevelCircuitBreakerConfig() { return partitionLevelCircuitBreakerConfig; } }
Similar as my comment in Configs.java - I would start with hard lower/upper boundaries on the config settings - we can always relax them - but never make them stricter (breaking change).
public int getAllowedExceptionCountToMaintainStatus(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } else { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites() / 2; case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } }
return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2;
public int getAllowedExceptionCountToMaintainStatus(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } else { switch (status) { case HealthyWithFailures: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites() / 2; case Healthy: case Unavailable: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } }
class ConsecutiveExceptionBasedCircuitBreaker { private static final Logger logger = LoggerFactory.getLogger(ConsecutiveExceptionBasedCircuitBreaker.class); private final PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig; public ConsecutiveExceptionBasedCircuitBreaker(PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig) { this.partitionLevelCircuitBreakerConfig = partitionLevelCircuitBreakerConfig; } public LocationSpecificHealthContext handleException(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: case HealthyTentative: exceptionCountAfterHandling++; int successCountAfterHandling = 0; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case Unavailable: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } } public LocationSpecificHealthContext handleSuccess(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); int successCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: exceptionCountAfterHandling = 0; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case HealthyTentative: successCountAfterHandling++; if (isReadOnlyRequest) { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } else { return new LocationSpecificHealthContext.Builder() .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()) .build(); } case Unavailable: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } } public boolean shouldHealthStatusBeDowngraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); return exceptionCountActual >= getAllowedExceptionCountToMaintainStatus(locationSpecificHealthContext.getLocationHealthStatus(), isReadOnlyRequest); } public boolean canHealthStatusBeUpgraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int successCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); return successCountActual >= getMinimumSuccessCountForStatusUpgrade(locationHealthStatus, isReadOnlyRequest); } public int getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } else { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalStateException("Unsupported health status: " + status); } } } public boolean isPartitionLevelCircuitBreakerEnabled() { return this.partitionLevelCircuitBreakerConfig.isPartitionLevelCircuitBreakerEnabled(); } public PartitionLevelCircuitBreakerConfig getPartitionLevelCircuitBreakerConfig() { return partitionLevelCircuitBreakerConfig; } }
class ConsecutiveExceptionBasedCircuitBreaker { private static final Logger logger = LoggerFactory.getLogger(ConsecutiveExceptionBasedCircuitBreaker.class); private final PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig; public ConsecutiveExceptionBasedCircuitBreaker(PartitionLevelCircuitBreakerConfig partitionLevelCircuitBreakerConfig) { this.partitionLevelCircuitBreakerConfig = partitionLevelCircuitBreakerConfig; } public LocationSpecificHealthContext handleException( LocationSpecificHealthContext locationSpecificHealthContext, PartitionKeyRangeWrapper partitionKeyRangeWrapper, String regionWithException, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: case HealthyTentative: exceptionCountAfterHandling++; int successCountAfterHandling = 0; LocationSpecificHealthContext.Builder builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case Unavailable: logger.warn("Region {} should not be handling failures in {} health status for partition key range : {} and collection RID : {}", regionWithException, locationHealthStatus.getStringifiedLocationHealthStatus(), partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive() + "-" + partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive(), partitionKeyRangeWrapper.getCollectionResourceId()); return locationSpecificHealthContext; default: throw new IllegalArgumentException("Unsupported health status : " + locationHealthStatus); } } public LocationSpecificHealthContext handleSuccess( LocationSpecificHealthContext locationSpecificHealthContext, PartitionKeyRangeWrapper partitionKeyRangeWrapper, String regionWithSuccess, boolean isReadOnlyRequest) { int exceptionCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); int successCountAfterHandling = (isReadOnlyRequest) ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); switch (locationHealthStatus) { case Healthy: return locationSpecificHealthContext; case HealthyWithFailures: exceptionCountAfterHandling = 0; LocationSpecificHealthContext.Builder builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case HealthyTentative: successCountAfterHandling++; builder = new LocationSpecificHealthContext.Builder() .withUnavailableSince(locationSpecificHealthContext.getUnavailableSince()) .withLocationHealthStatus(locationSpecificHealthContext.getLocationHealthStatus()) .withExceptionThresholdBreached(locationSpecificHealthContext.isExceptionThresholdBreached()); if (isReadOnlyRequest) { return builder .withSuccessCountForWriteForRecovery(locationSpecificHealthContext.getSuccessCountForWriteForRecovery()) .withExceptionCountForWriteForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking()) .withSuccessCountForReadForRecovery(successCountAfterHandling) .withExceptionCountForReadForCircuitBreaking(exceptionCountAfterHandling) .build(); } else { return builder .withSuccessCountForWriteForRecovery(successCountAfterHandling) .withExceptionCountForWriteForCircuitBreaking(exceptionCountAfterHandling) .withSuccessCountForReadForRecovery(locationSpecificHealthContext.getSuccessCountForReadForRecovery()) .withExceptionCountForReadForCircuitBreaking(locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking()) .build(); } case Unavailable: logger.warn("Region {} should not be handling successes in {} health status for partition key range : {} and collection RID : {}", regionWithSuccess, locationHealthStatus.getStringifiedLocationHealthStatus(), partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive() + "-" + partitionKeyRangeWrapper.getPartitionKeyRange().getMinInclusive(), partitionKeyRangeWrapper.getCollectionResourceId()); return locationSpecificHealthContext; default: throw new IllegalArgumentException("Unsupported health status : " + locationHealthStatus); } } public boolean shouldHealthStatusBeDowngraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int exceptionCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getExceptionCountForReadForCircuitBreaking() : locationSpecificHealthContext.getExceptionCountForWriteForCircuitBreaking(); return exceptionCountActual >= getAllowedExceptionCountToMaintainStatus(locationSpecificHealthContext.getLocationHealthStatus(), isReadOnlyRequest); } public boolean canHealthStatusBeUpgraded(LocationSpecificHealthContext locationSpecificHealthContext, boolean isReadOnlyRequest) { int successCountActual = isReadOnlyRequest ? locationSpecificHealthContext.getSuccessCountForReadForRecovery() : locationSpecificHealthContext.getSuccessCountForWriteForRecovery(); LocationHealthStatus locationHealthStatus = locationSpecificHealthContext.getLocationHealthStatus(); return successCountActual >= getMinimumSuccessCountForStatusUpgrade(locationHealthStatus, isReadOnlyRequest); } public int getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus status, boolean isReadOnlyRequest) { if (isReadOnlyRequest) { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForReads(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } else { switch (status) { case HealthyTentative: return this.partitionLevelCircuitBreakerConfig.getConsecutiveExceptionCountToleratedForWrites(); case Unavailable: case HealthyWithFailures: case Healthy: return 0; default: throw new IllegalArgumentException("Unsupported health status: " + status); } } } public boolean isPartitionLevelCircuitBreakerEnabled() { return this.partitionLevelCircuitBreakerConfig.isPartitionLevelCircuitBreakerEnabled(); } public PartitionLevelCircuitBreakerConfig getPartitionLevelCircuitBreakerConfig() { return partitionLevelCircuitBreakerConfig; } }
nit: not this PR but we should have all private methods throwing `IOException` and let the public methods handle try-catching. That way we don't need multiple layers of try-catching where we may accidentally try-catch multiple times.
private void eagerlyBufferResponseBody(HttpResponse<?> httpResponse, HttpURLConnection connection) { try { AccessibleByteArrayOutputStream outputStream = getAccessibleByteArrayOutputStream(connection); HttpResponseAccessHelper.setBody(httpResponse, BinaryData.fromByteBuffer(outputStream.toByteBuffer())); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } finally { connection.disconnect(); } }
throw LOGGER.logThrowableAsError(new UncheckedIOException(e));
private void eagerlyBufferResponseBody(HttpResponse<?> httpResponse, HttpURLConnection connection) { try { AccessibleByteArrayOutputStream outputStream = getAccessibleByteArrayOutputStream(connection); HttpResponseAccessHelper.setBody(httpResponse, BinaryData.fromByteBuffer(outputStream.toByteBuffer())); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } finally { connection.disconnect(); } }
class DefaultHttpClient implements HttpClient { private static final BinaryData EMPTY_BODY = BinaryData.fromBytes(new byte[0]); private static final ClientLogger LOGGER = new ClientLogger(DefaultHttpClient.class); private final long connectionTimeout; private final long readTimeout; private final ProxyOptions proxyOptions; DefaultHttpClient(Duration connectionTimeout, Duration readTimeout, ProxyOptions proxyOptions) { this.connectionTimeout = connectionTimeout == null ? -1 : connectionTimeout.toMillis(); this.readTimeout = readTimeout == null ? -1 : readTimeout.toMillis(); this.proxyOptions = proxyOptions; } /** * Synchronously send the HttpRequest. * * @param httpRequest The HTTP request being sent * @return The Response object */ @Override public Response<?> send(HttpRequest httpRequest) { if (httpRequest.getHttpMethod() == HttpMethod.PATCH) { return sendPatchViaSocket(httpRequest); } HttpURLConnection connection = connect(httpRequest); sendBody(httpRequest, connection); return receiveResponse(httpRequest, connection); } /** * Synchronously sends a PATCH request via a socket client. * * @param httpRequest The HTTP request being sent * @return The Response object */ private Response<?> sendPatchViaSocket(HttpRequest httpRequest) { try { return SocketClient.sendPatchRequest(httpRequest); } catch (IOException e) { throw LOGGER.logThrowableAsWarning(new UncheckedIOException(e)); } } /** * Open a connection based on the HttpRequest URL * * <p>If a proxy is specified, the authorization type will default to 'Basic' unless Digest authentication is * specified in the 'Authorization' header.</p> * * @param httpRequest The HTTP Request being sent * @return The HttpURLConnection object */ private HttpURLConnection connect(HttpRequest httpRequest) { try { HttpURLConnection connection; URL url = httpRequest.getUrl(); if (proxyOptions != null) { InetSocketAddress address = proxyOptions.getAddress(); if (address != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, address); connection = (HttpURLConnection) url.openConnection(proxy); if (proxyOptions.getUsername() != null && proxyOptions.getPassword() != null) { String authString = proxyOptions.getUsername() + ":" + proxyOptions.getPassword(); String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes()); connection.setRequestProperty("Proxy-Authorization", "Basic " + authStringEnc); } } else { throw LOGGER.logThrowableAsWarning(new ConnectException("Invalid proxy address")); } } else { connection = (HttpURLConnection) url.openConnection(); } if (connectionTimeout != -1) { connection.setConnectTimeout((int) connectionTimeout); } if (readTimeout != -1) { connection.setReadTimeout((int) readTimeout); } try { connection.setRequestMethod(httpRequest.getHttpMethod().toString()); } catch (ProtocolException e) { throw LOGGER.logThrowableAsError(new RuntimeException(e)); } for (HttpHeader header : httpRequest.getHeaders()) { for (String value : header.getValues()) { connection.addRequestProperty(header.getName(), value); } } return connection; } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } /** * Synchronously sends the content of an HttpRequest via an HttpUrlConnection instance. * * @param httpRequest The HTTP Request being sent * @param connection The HttpURLConnection that is being sent to */ private void sendBody(HttpRequest httpRequest, HttpURLConnection connection) { BinaryData body = httpRequest.getBody(); if (body == null) { return; } HttpMethod method = httpRequest.getHttpMethod(); switch (httpRequest.getHttpMethod()) { case GET: case HEAD: return; case OPTIONS: case TRACE: case CONNECT: case POST: case PUT: case DELETE: connection.setDoOutput(true); try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) { body.writeTo(os); os.flush(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } return; default: throw LOGGER.logThrowableAsError(new IllegalStateException("Unknown HTTP Method: " + method)); } } /** * Receive the response from the remote server * * @param httpRequest The HTTP Request being sent * @param connection The HttpURLConnection being sent to * @return A HttpResponse object */ private Response<?> receiveResponse(HttpRequest httpRequest, HttpURLConnection connection) { HttpHeaders responseHeaders = getResponseHeaders(connection); HttpResponse<?> httpResponse = createHttpResponse(httpRequest, connection); if (isTextEventStream(responseHeaders)) { ServerSentEventListener listener = httpRequest.getServerSentEventListener(); if (listener == null) { throw LOGGER.logThrowableAsError(new RuntimeException(NO_LISTENER_ERROR_MESSAGE)); } if (connection.getErrorStream() == null) { try { processTextEventStream(httpRequest, httpRequestConsumer -> this.send(httpRequest), connection.getInputStream(), listener, LOGGER); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } finally { connection.disconnect(); } } } else { HttpRequestMetadata metadata = httpRequest.getMetadata(); if (metadata != null && metadata.getResponseBodyHandling() != null) { switch (metadata.getResponseBodyHandling()) { case IGNORE: ignoreResponseBody(httpResponse, connection); break; case STREAM: setStreamingResponseBody(httpResponse, connection); break; case BUFFER: case DESERIALIZE: default: eagerlyBufferResponseBody(httpResponse, connection); } } else { eagerlyBufferResponseBody(httpResponse, connection); } } return httpResponse; } private HttpResponse<?> createHttpResponse(HttpRequest httpRequest, HttpURLConnection connection) { try { return new HttpResponse<>(httpRequest, connection.getResponseCode(), getResponseHeaders(connection), null); } catch (IOException e) { connection.disconnect(); throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } private static boolean isTextEventStream(HttpHeaders responseHeaders) { if (responseHeaders != null) { return ServerSentEventUtil.isTextEventStreamContentType(responseHeaders.getValue(HttpHeaderName.CONTENT_TYPE)); } return false; } private void setStreamingResponseBody(HttpResponse<?> httpResponse, HttpURLConnection connection) { try { HttpResponseAccessHelper.setBody(httpResponse, BinaryData.fromStream(connection.getInputStream())); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } private void ignoreResponseBody(HttpResponse<?> httpResponse, HttpURLConnection connection) { HttpResponseAccessHelper.setBody(httpResponse, EMPTY_BODY); connection.disconnect(); } private HttpHeaders getResponseHeaders(HttpURLConnection connection) { Map<String, List<String>> hucHeaders = connection.getHeaderFields(); HttpHeaders responseHeaders = new HttpHeaders(hucHeaders.size()); for (Map.Entry<String, List<String>> entry : hucHeaders.entrySet()) { if (entry.getKey() != null) { responseHeaders.add(HttpHeaderName.fromString(entry.getKey()), entry.getValue()); } } return responseHeaders; } private static AccessibleByteArrayOutputStream getAccessibleByteArrayOutputStream(HttpURLConnection connection) throws IOException { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); try (InputStream errorStream = connection.getErrorStream(); InputStream inputStream = (errorStream == null) ? connection.getInputStream() : errorStream) { byte[] buffer = new byte[8192]; int length; while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } } return outputStream; } private static class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; private static final SSLSocketFactory SSL_SOCKET_FACTORY = (SSLSocketFactory) SSLSocketFactory.getDefault(); /** * Opens a socket connection, then writes the PATCH request across the connection and reads the response * * @param httpRequest The HTTP Request being sent * @return an instance of HttpUrlConnectionResponse * @throws ProtocolException If the protocol is not HTTP or HTTPS * @throws IOException If an I/O error occurs */ public static Response<?> sendPatchRequest(HttpRequest httpRequest) throws IOException { final URL requestUrl = httpRequest.getUrl(); final String protocol = requestUrl.getProtocol(); final String host = requestUrl.getHost(); final int port = requestUrl.getPort(); switch (protocol) { case "https": try (SSLSocket socket = (SSLSocket) SSL_SOCKET_FACTORY.createSocket(host, port)) { return doInputOutput(httpRequest, socket); } case "http": try (Socket socket = new Socket(host, port)) { return doInputOutput(httpRequest, socket); } default: throw LOGGER.logThrowableAsWarning( new ProtocolException("Only HTTP and HTTPS are supported by this client.")); } } /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param socket An instance of the SocketClient * @return an instance of Response */ @SuppressWarnings("deprecation") private static Response<?> doInputOutput(HttpRequest httpRequest, Socket socket) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); if (!"keep-alive".equalsIgnoreCase(httpRequest.getHeaders().getValue(HttpHeaderName.CONNECTION))) { httpRequest.getHeaders().set(HttpHeaderName.CONNECTION, "close"); } try (BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream())) { buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, in); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { httpRequest.setUrl(new URL(httpRequest.getUrl(), redirectLocation)); } return sendPatchRequest(httpRequest); } return response; } } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * HttpUrlConnectionResponse * * @param httpRequest The HTTP Request being sent * @param reader the input stream from the socket * @return an instance of HttpUrlConnectionResponse * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedReader reader) throws IOException { String statusLine = reader.readLine(); int dotIndex = statusLine.indexOf('.'); int statusCode = Integer.parseInt(statusLine.substring(dotIndex + 3, dotIndex + 6)); HttpHeaders headers = new HttpHeaders(); String line; while ((line = reader.readLine()) != null && !line.isEmpty()) { int split = line.indexOf(':'); String key = line.substring(0, split); String value = line.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); } StringBuilder bodyString = new StringBuilder(); while ((line = reader.readLine()) != null) { bodyString.append(line); } BinaryData body = BinaryData.fromByteBuffer(ByteBuffer.wrap(bodyString.toString().getBytes())); return new HttpResponse<>(httpRequest, statusCode, headers, body); } } }
class DefaultHttpClient implements HttpClient { private static final BinaryData EMPTY_BODY = BinaryData.fromBytes(new byte[0]); private static final ClientLogger LOGGER = new ClientLogger(DefaultHttpClient.class); private final long connectionTimeout; private final long readTimeout; private final ProxyOptions proxyOptions; DefaultHttpClient(Duration connectionTimeout, Duration readTimeout, ProxyOptions proxyOptions) { this.connectionTimeout = connectionTimeout == null ? -1 : connectionTimeout.toMillis(); this.readTimeout = readTimeout == null ? -1 : readTimeout.toMillis(); this.proxyOptions = proxyOptions; } /** * Synchronously send the HttpRequest. * * @param httpRequest The HTTP request being sent * @return The Response object */ @Override public Response<?> send(HttpRequest httpRequest) { if (httpRequest.getHttpMethod() == HttpMethod.PATCH) { return sendPatchViaSocket(httpRequest); } HttpURLConnection connection = connect(httpRequest); sendBody(httpRequest, connection); return receiveResponse(httpRequest, connection); } /** * Synchronously sends a PATCH request via a socket client. * * @param httpRequest The HTTP request being sent * @return The Response object */ private Response<?> sendPatchViaSocket(HttpRequest httpRequest) { try { return SocketClient.sendPatchRequest(httpRequest); } catch (IOException e) { throw LOGGER.logThrowableAsWarning(new UncheckedIOException(e)); } } /** * Open a connection based on the HttpRequest URL * * <p>If a proxy is specified, the authorization type will default to 'Basic' unless Digest authentication is * specified in the 'Authorization' header.</p> * * @param httpRequest The HTTP Request being sent * @return The HttpURLConnection object */ private HttpURLConnection connect(HttpRequest httpRequest) { try { HttpURLConnection connection; URL url = httpRequest.getUrl(); if (proxyOptions != null) { InetSocketAddress address = proxyOptions.getAddress(); if (address != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, address); connection = (HttpURLConnection) url.openConnection(proxy); if (proxyOptions.getUsername() != null && proxyOptions.getPassword() != null) { String authString = proxyOptions.getUsername() + ":" + proxyOptions.getPassword(); String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes()); connection.setRequestProperty("Proxy-Authorization", "Basic " + authStringEnc); } } else { throw LOGGER.logThrowableAsWarning(new ConnectException("Invalid proxy address")); } } else { connection = (HttpURLConnection) url.openConnection(); } if (connectionTimeout != -1) { connection.setConnectTimeout((int) connectionTimeout); } if (readTimeout != -1) { connection.setReadTimeout((int) readTimeout); } try { connection.setRequestMethod(httpRequest.getHttpMethod().toString()); } catch (ProtocolException e) { throw LOGGER.logThrowableAsError(new RuntimeException(e)); } for (HttpHeader header : httpRequest.getHeaders()) { for (String value : header.getValues()) { connection.addRequestProperty(header.getName().toString(), value); } } return connection; } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } /** * Synchronously sends the content of an HttpRequest via an HttpUrlConnection instance. * * @param httpRequest The HTTP Request being sent * @param connection The HttpURLConnection that is being sent to */ private void sendBody(HttpRequest httpRequest, HttpURLConnection connection) { BinaryData body = httpRequest.getBody(); if (body == null) { return; } HttpMethod method = httpRequest.getHttpMethod(); switch (httpRequest.getHttpMethod()) { case GET: case HEAD: return; case OPTIONS: case TRACE: case CONNECT: case POST: case PUT: case DELETE: connection.setDoOutput(true); try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) { body.writeTo(os); os.flush(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } return; default: throw LOGGER.logThrowableAsError(new IllegalStateException("Unknown HTTP Method: " + method)); } } /** * Receive the response from the remote server * * @param httpRequest The HTTP Request being sent * @param connection The HttpURLConnection being sent to * @return A HttpResponse object */ private Response<?> receiveResponse(HttpRequest httpRequest, HttpURLConnection connection) { HttpHeaders responseHeaders = getResponseHeaders(connection); HttpResponse<?> httpResponse = createHttpResponse(httpRequest, connection); if (isTextEventStream(responseHeaders)) { try { ServerSentEventListener listener = httpRequest.getServerSentEventListener(); if (listener == null) { throw LOGGER.logThrowableAsError(new RuntimeException(NO_LISTENER_ERROR_MESSAGE)); } if (connection.getErrorStream() == null) { processTextEventStream(httpRequest, httpRequestConsumer -> this.send(httpRequest), connection.getInputStream(), listener, LOGGER); } } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } finally { connection.disconnect(); } } else { ResponseBodyMode responseBodyMode = httpRequest.getMetadata().getResponseBodyMode(); if (responseBodyMode == null) { HttpHeader contentType = httpResponse.getHeaders().get(CONTENT_TYPE); String contentTypeString = contentType == null ? null : contentType.getValue(); if (APPLICATION_OCTET_STREAM.equalsIgnoreCase(contentTypeString)) { responseBodyMode = STREAM; } else { responseBodyMode = BUFFER; } httpRequest.getMetadata().setResponseBodyMode(responseBodyMode); } switch (responseBodyMode) { case IGNORE: HttpResponseAccessHelper.setBody(httpResponse, EMPTY_BODY); connection.disconnect(); break; case STREAM: streamResponseBody(httpResponse, connection); break; case BUFFER: case DESERIALIZE: default: eagerlyBufferResponseBody(httpResponse, connection); } } return httpResponse; } private HttpResponse<?> createHttpResponse(HttpRequest httpRequest, HttpURLConnection connection) { try { return new HttpResponse<>(httpRequest, connection.getResponseCode(), getResponseHeaders(connection), null); } catch (IOException e) { connection.disconnect(); throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } private static boolean isTextEventStream(HttpHeaders responseHeaders) { if (responseHeaders != null) { return ServerSentEventUtil.isTextEventStreamContentType(responseHeaders.getValue(CONTENT_TYPE)); } return false; } private void streamResponseBody(HttpResponse<?> httpResponse, HttpURLConnection connection) { try { HttpResponseAccessHelper.setBody(httpResponse, BinaryData.fromStream(connection.getInputStream())); } catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } } private HttpHeaders getResponseHeaders(HttpURLConnection connection) { Map<String, List<String>> hucHeaders = connection.getHeaderFields(); HttpHeaders responseHeaders = new HttpHeaders(hucHeaders.size()); for (Map.Entry<String, List<String>> entry : hucHeaders.entrySet()) { if (entry.getKey() != null) { responseHeaders.add(HttpHeaderName.fromString(entry.getKey()), entry.getValue()); } } return responseHeaders; } private static AccessibleByteArrayOutputStream getAccessibleByteArrayOutputStream(HttpURLConnection connection) throws IOException { AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); try (InputStream errorStream = connection.getErrorStream(); InputStream inputStream = (errorStream == null) ? connection.getInputStream() : errorStream) { byte[] buffer = new byte[8192]; int length; while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } } return outputStream; } private static class SocketClient { private static final String HTTP_VERSION = " HTTP/1.1"; private static final SSLSocketFactory SSL_SOCKET_FACTORY = (SSLSocketFactory) SSLSocketFactory.getDefault(); /** * Opens a socket connection, then writes the PATCH request across the connection and reads the response * * @param httpRequest The HTTP Request being sent * @return an instance of HttpUrlConnectionResponse * @throws ProtocolException If the protocol is not HTTP or HTTPS * @throws IOException If an I/O error occurs */ public static Response<?> sendPatchRequest(HttpRequest httpRequest) throws IOException { final URL requestUrl = httpRequest.getUrl(); final String protocol = requestUrl.getProtocol(); final String host = requestUrl.getHost(); final int port = requestUrl.getPort(); switch (protocol) { case "https": try (SSLSocket socket = (SSLSocket) SSL_SOCKET_FACTORY.createSocket(host, port)) { return doInputOutput(httpRequest, socket); } case "http": try (Socket socket = new Socket(host, port)) { return doInputOutput(httpRequest, socket); } default: throw LOGGER.logThrowableAsWarning( new ProtocolException("Only HTTP and HTTPS are supported by this client.")); } } /** * Calls buildAndSend to send a String representation of the request across the output stream, then calls * buildResponse to get an instance of HttpUrlConnectionResponse from the input stream * * @param httpRequest The HTTP Request being sent * @param socket An instance of the SocketClient * @return an instance of Response */ @SuppressWarnings("deprecation") private static Response<?> doInputOutput(HttpRequest httpRequest, Socket socket) throws IOException { httpRequest.getHeaders().set(HttpHeaderName.HOST, httpRequest.getUrl().getHost()); if (!"keep-alive".equalsIgnoreCase(httpRequest.getHeaders().getValue(HttpHeaderName.CONNECTION))) { httpRequest.getHeaders().set(HttpHeaderName.CONNECTION, "close"); } try (BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream())) { buildAndSend(httpRequest, out); Response<?> response = buildResponse(httpRequest, in); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); String redirectLocation = (locationHeader == null) ? null : locationHeader.getValue(); if (redirectLocation != null) { if (redirectLocation.startsWith("http")) { httpRequest.setUrl(redirectLocation); } else { httpRequest.setUrl(new URL(httpRequest.getUrl(), redirectLocation)); } return sendPatchRequest(httpRequest); } return response; } } /** * Converts an instance of HttpRequest to a String representation for sending over the output stream * * @param httpRequest The HTTP Request being sent * @param out output stream for writing the request * @throws IOException If an I/O error occurs */ private static void buildAndSend(HttpRequest httpRequest, OutputStreamWriter out) throws IOException { final StringBuilder request = new StringBuilder(); request.append("PATCH ").append(httpRequest.getUrl().getPath()).append(HTTP_VERSION).append("\r\n"); if (httpRequest.getHeaders().getSize() > 0) { for (HttpHeader header : httpRequest.getHeaders()) { header.getValues() .forEach(value -> request.append(header.getName()).append(':').append(value).append("\r\n")); } } if (httpRequest.getBody() != null) { request.append("\r\n").append(httpRequest.getBody().toString()).append("\r\n"); } out.write(request.toString()); out.flush(); } /** * Reads the response from the input stream and extracts the information needed to construct an instance of * HttpUrlConnectionResponse * * @param httpRequest The HTTP Request being sent * @param reader the input stream from the socket * @return an instance of HttpUrlConnectionResponse * @throws IOException If an I/O error occurs */ private static Response<?> buildResponse(HttpRequest httpRequest, BufferedReader reader) throws IOException { String statusLine = reader.readLine(); int dotIndex = statusLine.indexOf('.'); int statusCode = Integer.parseInt(statusLine.substring(dotIndex + 3, dotIndex + 6)); HttpHeaders headers = new HttpHeaders(); String line; while ((line = reader.readLine()) != null && !line.isEmpty()) { int split = line.indexOf(':'); String key = line.substring(0, split); String value = line.substring(split + 1).trim(); headers.add(HttpHeaderName.fromString(key), value); } StringBuilder bodyString = new StringBuilder(); while ((line = reader.readLine()) != null) { bodyString.append(line); } BinaryData body = BinaryData.fromByteBuffer(ByteBuffer.wrap(bodyString.toString().getBytes())); return new HttpResponse<>(httpRequest, statusCode, headers, body); } } }
May be a little pedantic, would it be useful to have the exception being resumed here be maintained? The code would have to duplicate a bit where there wouldn't be a `switchIfEmpty` and that code block duplicate (mostly), ```java if (options.isBrokerEnabled() && options.useOperatingSystemAccount()) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> { Mono<IAuthenticationResult> acquireToken = Mono.fromFuture(() -> pc.acquireToken( buildInteractiveRequestParameters(request, loginHint, redirectUri).build())); return acquireToken.onErrorMap(t -> { t.addSuppressed(e); return new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t); }); })) .map(MsalToken::new); } else { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); Mono<IAuthenticationResult> acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } ``` Right now, the error resumed there is lost, which may contain some useful information on fixing a problem with brokering.
return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } })
.onErrorResume(e -> Mono.empty());
return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE." + " Fore more details refer to the troubleshooting guidelines here at" + " https: } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } for (String scope : scopes) { try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER); List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { String scope = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } return Mono.using(() -> powershellManager, manager -> manager.initSession().flatMap(m -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return m.runCommand(azAccountsCommand).flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Az.Account module with version >= 2.2.0 is not installed. " + "It needs to be installed to use Azure PowerShell " + "Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl '" + scope + "' | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return m.runCommand(command).flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time).withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }), PowershellManager::close); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, false) ).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, true) ).map(MsalToken::new)) ); } private CompletableFuture<IAuthenticationResult> acquireTokenFromPublicClientSilently(TokenRequestContext request, PublicClientApplication pc, IAccount account, boolean forceRefresh ) { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (forceRefresh) { parametersBuilder.forceRefresh(true); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } } private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return authenticateWithConfidentialClientCache(request, null); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request, IAccount account) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (account != null) { parametersBuilder.account(account); } try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } }) .switchIfEmpty(Mono.defer(() -> { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); })) .doOnError(t -> !(t instanceof ClientAuthenticationException), t -> { throw new ClientAuthenticationException("Failed to acquire token with Interactive Browser Authentication.", null, t); }) .map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } } finally { String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); if (connection != null) { connection.disconnect(); } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 403) { if (connection.getResponseMessage() .contains("A socket operation was attempted to an unreachable network")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Managed Identity response was not in the expected format." + " See the inner exception for details.", new Exception(connection.getResponseMessage()))); } } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE." + " Fore more details refer to the troubleshooting guidelines here at" + " https: } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } for (String scope : scopes) { try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER); List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { String scope = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } return Mono.using(() -> powershellManager, manager -> manager.initSession().flatMap(m -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return m.runCommand(azAccountsCommand).flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Az.Account module with version >= 2.2.0 is not installed. " + "It needs to be installed to use Azure PowerShell " + "Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl '" + scope + "' | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return m.runCommand(command).flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time).withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }), PowershellManager::close); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, false) ).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, true) ).map(MsalToken::new)) ); } private CompletableFuture<IAuthenticationResult> acquireTokenFromPublicClientSilently(TokenRequestContext request, PublicClientApplication pc, IAccount account, boolean forceRefresh ) { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (forceRefresh) { parametersBuilder.forceRefresh(true); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } } private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return authenticateWithConfidentialClientCache(request, null); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request, IAccount account) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (account != null) { parametersBuilder.account(account); } try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } }) .switchIfEmpty(Mono.defer(() -> { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); })) .onErrorMap(t -> !(t instanceof ClientAuthenticationException), t -> { throw new ClientAuthenticationException("Failed to acquire token with Interactive Browser Authentication.", null, t); }) .map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } } finally { String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); if (connection != null) { connection.disconnect(); } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 403) { if (connection.getResponseMessage() .contains("A socket operation was attempted to an unreachable network")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Managed Identity response was not in the expected format." + " See the inner exception for details.", new Exception(connection.getResponseMessage()))); } } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
The error message is being ignored right now because it is really control flow. MSAL will either return a valid token or throw an exception. This operation is speculative; for various reasons automatic sign-in might fail and we fall back to showing the UI. Preserving the error here doesn't provide any useful log context, nor does it provide anything actionable down the line. If you feel strongly here I'll make a change, but I don't see the upside. I will put a comment in explaining why we're ignoring it, though.
return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } })
.onErrorResume(e -> Mono.empty());
return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE." + " Fore more details refer to the troubleshooting guidelines here at" + " https: } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } for (String scope : scopes) { try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER); List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { String scope = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } return Mono.using(() -> powershellManager, manager -> manager.initSession().flatMap(m -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return m.runCommand(azAccountsCommand).flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Az.Account module with version >= 2.2.0 is not installed. " + "It needs to be installed to use Azure PowerShell " + "Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl '" + scope + "' | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return m.runCommand(command).flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time).withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }), PowershellManager::close); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, false) ).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, true) ).map(MsalToken::new)) ); } private CompletableFuture<IAuthenticationResult> acquireTokenFromPublicClientSilently(TokenRequestContext request, PublicClientApplication pc, IAccount account, boolean forceRefresh ) { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (forceRefresh) { parametersBuilder.forceRefresh(true); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } } private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return authenticateWithConfidentialClientCache(request, null); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request, IAccount account) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (account != null) { parametersBuilder.account(account); } try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } }) .switchIfEmpty(Mono.defer(() -> { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); })) .doOnError(t -> !(t instanceof ClientAuthenticationException), t -> { throw new ClientAuthenticationException("Failed to acquire token with Interactive Browser Authentication.", null, t); }) .map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } } finally { String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); if (connection != null) { connection.disconnect(); } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 403) { if (connection.getResponseMessage() .contains("A socket operation was attempted to an unreachable network")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Managed Identity response was not in the expected format." + " See the inner exception for details.", new Exception(connection.getResponseMessage()))); } } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE." + " Fore more details refer to the troubleshooting guidelines here at" + " https: } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } for (String scope : scopes) { try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER); List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { String scope = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } return Mono.using(() -> powershellManager, manager -> manager.initSession().flatMap(m -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return m.runCommand(azAccountsCommand).flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Az.Account module with version >= 2.2.0 is not installed. " + "It needs to be installed to use Azure PowerShell " + "Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl '" + scope + "' | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return m.runCommand(command).flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time).withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }), PowershellManager::close); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, false) ).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, true) ).map(MsalToken::new)) ); } private CompletableFuture<IAuthenticationResult> acquireTokenFromPublicClientSilently(TokenRequestContext request, PublicClientApplication pc, IAccount account, boolean forceRefresh ) { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (forceRefresh) { parametersBuilder.forceRefresh(true); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } } private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return authenticateWithConfidentialClientCache(request, null); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request, IAccount account) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (account != null) { parametersBuilder.account(account); } try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } }) .switchIfEmpty(Mono.defer(() -> { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); })) .onErrorMap(t -> !(t instanceof ClientAuthenticationException), t -> { throw new ClientAuthenticationException("Failed to acquire token with Interactive Browser Authentication.", null, t); }) .map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } } finally { String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); if (connection != null) { connection.disconnect(); } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 403) { if (connection.getResponseMessage() .contains("A socket operation was attempted to an unreachable network")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Managed Identity response was not in the expected format." + " See the inner exception for details.", new Exception(connection.getResponseMessage()))); } } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
Makes sense, didn't really know that, was more worried about losing exception information if the fallback failed as well but this isn't really a case where the exception being ignored is meaningful. Given all that, mind leaving a small comment about why it's okay for the exception to be lost in this scenario.
return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } })
.onErrorResume(e -> Mono.empty());
return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = buildUsernamePasswordFlowParameters(request, username, password); return pc.acquireToken(userNamePasswordParametersBuilder.build()); }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE." + " Fore more details refer to the troubleshooting guidelines here at" + " https: } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } for (String scope : scopes) { try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER); List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { String scope = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } return Mono.using(() -> powershellManager, manager -> manager.initSession().flatMap(m -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return m.runCommand(azAccountsCommand).flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Az.Account module with version >= 2.2.0 is not installed. " + "It needs to be installed to use Azure PowerShell " + "Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl '" + scope + "' | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return m.runCommand(command).flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time).withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }), PowershellManager::close); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, false) ).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, true) ).map(MsalToken::new)) ); } private CompletableFuture<IAuthenticationResult> acquireTokenFromPublicClientSilently(TokenRequestContext request, PublicClientApplication pc, IAccount account, boolean forceRefresh ) { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (forceRefresh) { parametersBuilder.forceRefresh(true); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } } private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return authenticateWithConfidentialClientCache(request, null); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request, IAccount account) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (account != null) { parametersBuilder.account(account); } try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } }) .switchIfEmpty(Mono.defer(() -> { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); })) .doOnError(t -> !(t instanceof ClientAuthenticationException), t -> { throw new ClientAuthenticationException("Failed to acquire token with Interactive Browser Authentication.", null, t); }) .map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } } finally { String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); if (connection != null) { connection.disconnect(); } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 403) { if (connection.getResponseMessage() .contains("A socket operation was attempted to an unreachable network")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Managed Identity response was not in the expected format." + " See the inner exception for details.", new Exception(connection.getResponseMessage()))); } } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
class IdentityClient extends IdentityClientBase { private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessorWithCae; private final SynchronizedAccessor<ConfidentialClientApplication> managedIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> workloadIdentityConfidentialClientApplicationAccessor; private final SynchronizedAccessor<String> clientAssertionAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, byte[] certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { super(tenantId, clientId, clientSecret, certificatePath, clientAssertionFilePath, resourceId, clientAssertionSupplier, certificate, certificatePassword, isSharedTokenCacheCredential, clientAssertionTimeout, options); this.publicClientApplicationAccessor = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, false)); this.publicClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getPublicClientApplication(isSharedTokenCacheCredential, true)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(false)); this.confidentialClientApplicationAccessorWithCae = new SynchronizedAccessor<>(() -> getConfidentialClientApplication(true)); this.managedIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getManagedIdentityConfidentialClientApplication); this.workloadIdentityConfidentialClientApplicationAccessor = new SynchronizedAccessor<>(this::getWorkloadIdentityConfidentialClientApplication); Duration cacheTimeout = (clientAssertionTimeout == null) ? Duration.ofMinutes(5) : clientAssertionTimeout; this.clientAssertionAccessor = new SynchronizedAccessor<>(this::parseClientAssertion, cacheTimeout); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication(boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getConfidentialClient(enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getManagedIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getManagedIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } private Mono<ConfidentialClientApplication> getWorkloadIdentityConfidentialClientApplication() { return Mono.defer(() -> { try { return Mono.just(super.getWorkloadIdentityConfidentialClient()); } catch (RuntimeException e) { return Mono.error(e); } }); } @Override Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext) { ManagedIdentityParameters parameters = options.getManagedIdentityParameters(); ManagedIdentityType managedIdentityType = options.getManagedIdentityType(); switch (managedIdentityType) { case APP_SERVICE: return authenticateToManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getMsiEndpoint(), parameters.getMsiSecret(), tokenRequestContext); case SERVICE_FABRIC: return authenticateToServiceFabricManagedIdentityEndpoint(parameters.getIdentityEndpoint(), parameters.getIdentityHeader(), parameters.getIdentityServerThumbprint(), tokenRequestContext); case ARC: return authenticateToArcManagedIdentityEndpoint(parameters.getIdentityEndpoint(), tokenRequestContext); case AKS: return authenticateWithExchangeToken(tokenRequestContext); case VM: return authenticateToIMDSEndpoint(tokenRequestContext); default: return Mono.error(LOGGER.logExceptionAsError( new CredentialUnavailableException("Unknown Managed Identity type, authentication not available."))); } } private Mono<String> parseClientAssertion() { return Mono.fromCallable(() -> { if (clientAssertionFilePath != null) { byte[] encoded = Files.readAllBytes(Paths.get(clientAssertionFilePath)); return new String(encoded, StandardCharsets.UTF_8); } else { throw LOGGER.logExceptionAsError(new IllegalStateException( "Client Assertion File Path is not provided." + " It should be provided to authenticate with client assertion." )); } }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential, boolean enableCae) { return Mono.defer(() -> { try { return Mono.just(this.getPublicClient(sharedTokenCacheCredential, enableCae)); } catch (RuntimeException e) { return Mono.error(e); } }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); String cachedRefreshToken = cacheAccessor.getIntelliJCredentialsFromIdentityMsalCache(); if (!CoreUtils.isNullOrEmpty(cachedRefreshToken)) { RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), cachedRefreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } IntelliJAuthMethodDetails authDetails; try { authDetails = cacheAccessor.getAuthDetailsIfAvailable(); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available.", e))); } if (authDetails == null) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in the IDE." + " Fore more details refer to the troubleshooting guidelines here at" + " https: } String authType = authDetails.getAuthMethod(); if ("SP".equalsIgnoreCase(authType)) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl) .instanceDiscovery(options.isInstanceDiscoveryEnabled()); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if ("DC".equalsIgnoreCase(authType)) { LOGGER.verbose("IntelliJ Authentication => Device Code Authentication scheme detected in Azure Tools" + " for IntelliJ Plugin."); if (isADFSTenant()) { LOGGER.verbose("IntelliJ Authentication => The input tenant is detected to be ADFS and" + " the ADFS tenants are not supported via IntelliJ Authentication currently."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported."))); } try { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } } else { LOGGER.verbose("IntelliJ Authentication = > Only Service Principal and Device Code Authentication" + " schemes are currently supported via IntelliJ Credential currently. Please ensure you used one" + " of those schemes from Azure Tools for IntelliJ plugin."); return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE."))); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { StringBuilder azCommand = new StringBuilder("az account get-access-token --output json --resource "); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } azCommand.append(scopes); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azCommand.append(" --tenant ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureCLIAuthentication(azCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure Developer CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureDeveloperCli(TokenRequestContext request) { StringBuilder azdCommand = new StringBuilder("azd auth token --output json --scope "); List<String> scopes = request.getScopes(); if (scopes.size() == 0) { return Mono.error(LOGGER.logExceptionAsError(new IllegalArgumentException("Missing scope in request"))); } for (String scope : scopes) { try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { return Mono.error(LOGGER.logExceptionAsError(ex)); } } azdCommand.append(String.join(" --scope ", scopes)); try { String tenant = IdentityUtil.resolveTenantId(tenantId, request, options); ValidationUtil.validateTenantIdCharacterRange(tenant, LOGGER); if (!CoreUtils.isNullOrEmpty(tenant) && !tenant.equals(IdentityUtil.DEFAULT_TENANT)) { azdCommand.append(" --tenant-id ").append(tenant); } } catch (ClientAuthenticationException | IllegalArgumentException e) { return Mono.error(e); } try { AccessToken token = getTokenFromAzureDeveloperCLIAuthentication(azdCommand); return Mono.just(token); } catch (RuntimeException e) { return Mono.error(e instanceof CredentialUnavailableException ? LoggingUtil.logCredentialUnavailableException(LOGGER, options, (CredentialUnavailableException) e) : LOGGER.logExceptionAsError(e)); } } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER); List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage() + ". To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure PowerShell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure PowerShell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, (last))); })); } /** * Asynchronously acquire a token from Active Directory with Azure PowerShell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithOBO(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken(buildOBOFlowParameters(request))) .map(MsalToken::new)); } private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { String scope = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scope); } catch (IllegalArgumentException ex) { throw LOGGER.logExceptionAsError(ex); } return Mono.using(() -> powershellManager, manager -> manager.initSession().flatMap(m -> { String azAccountsCommand = "Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru"; return m.runCommand(azAccountsCommand).flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Az.Account module with version >= 2.2.0 is not installed. " + "It needs to be installed to use Azure PowerShell " + "Credential."))); } LOGGER.verbose("Az.accounts module was found installed."); String command = "Get-AzAccessToken -ResourceUrl '" + scope + "' | ConvertTo-Json"; LOGGER.verbose("Azure Powershell Authentication => Executing the command `{}` in Azure " + "Powershell to retrieve the Access Token.", command); return m.runCommand(command).flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell."))); } try { LOGGER.verbose("Azure Powershell Authentication => Attempting to deserialize the " + "received response from Azure Powershell."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time).withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); }); }), PowershellManager::close); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = buildConfidentialClientParameters(request); return confidentialClient.acquireToken(builder.build()); } )).map(MsalToken::new); } private SynchronizedAccessor<ConfidentialClientApplication> getConfidentialClientInstance(TokenRequestContext requestContext) { return requestContext.isCaeEnabled() ? confidentialClientApplicationAccessorWithCae : confidentialClientApplicationAccessor; } private ClientCredentialParameters.ClientCredentialParametersBuilder buildConfidentialClientParameters(TokenRequestContext request) { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (clientAssertionSupplier != null) { builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplier.get())); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } return builder; } public Mono<AccessToken> authenticateWithManagedIdentityConfidentialClient(TokenRequestContext request) { return managedIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } public Mono<AccessToken> authenticateWithWorkloadIdentityConfidentialClient(TokenRequestContext request) { return workloadIdentityConfidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); return confidentialClient.acquireToken(builder.build()); } )).onErrorMap(t -> new CredentialUnavailableException("Managed Identity authentication is not available.", t)) .map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password. To mitigate this issue, please refer to the troubleshooting guidelines " + "here at https: null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, false) ).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, account, true) ).map(MsalToken::new)) ); } private CompletableFuture<IAuthenticationResult> acquireTokenFromPublicClientSilently(TokenRequestContext request, PublicClientApplication pc, IAccount account, boolean forceRefresh ) { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (forceRefresh) { parametersBuilder.forceRefresh(true); } if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } parametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } } private SynchronizedAccessor<PublicClientApplication> getPublicClientInstance(TokenRequestContext request) { return request.isCaeEnabled() ? publicClientApplicationAccessorWithCae : publicClientApplicationAccessor; } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return authenticateWithConfidentialClientCache(request, null); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to log in to acquire the last token * * @return a Publisher that emits an AccessToken */ @SuppressWarnings("deprecation") public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request, IAccount account) { return getConfidentialClientInstance(request).getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); if (account != null) { parametersBuilder.account(account); } try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(LOGGER.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return getPublicClientInstance(request).getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = buildDeviceCodeFlowParameters(request, deviceCodeConsumer); return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code.", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Studio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported. " + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = null; try { credential = accessor.getCredentials("VS Code Azure", cloud); } catch (CredentialUnavailableException e) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, e)); } RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return getPublicClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("Failed to acquire token with" + " VS code credential." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = getConfidentialClientInstance(request).getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); acquireToken = publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(LOGGER.logExceptionAsError(new RuntimeException(e))); } return getPublicClientInstance(request).getValue().flatMap(pc -> { if (options.isBrokerEnabled() && options.useDefaultBrokerAccount()) { return Mono.fromFuture(() -> acquireTokenFromPublicClientSilently(request, pc, null, false)) .onErrorResume(e -> Mono.empty()); } else { return Mono.empty(); } }) .switchIfEmpty(Mono.defer(() -> { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = buildInteractiveRequestParameters(request, loginHint, redirectUri); SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); })) .onErrorMap(t -> !(t instanceof ClientAuthenticationException), t -> { throw new ClientAuthenticationException("Failed to acquire token with Interactive Browser Authentication.", null, t); }) .map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { SynchronizedAccessor<PublicClientApplication> publicClient = getPublicClientInstance(request); return publicClient.getValue() .flatMap(pc -> Mono.fromFuture(pc::getAccounts)) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache."))); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { accounts.putIfAbsent(cached.homeAccountId(), cached); } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication unavailable. " + "Multiple accounts were found in the cache. Use username and tenant id to disambiguate.") ); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; String payload = identityEndpoint + "?resource=" + urlEncode(ScopeUtil.scopesToResource(request.getScopes())) + "&api-version=" + ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION; URL url = getUrl(payload); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); } catch (IOException e) { if (connection == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } } finally { String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); if (connection != null) { connection.disconnect(); } if (secretKey == null) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + secretKey); connection.setRequestProperty("Metadata", "true"); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithExchangeToken(TokenRequestContext request) { return clientAssertionAccessor.getValue() .flatMap(assertionToken -> Mono.fromCallable(() -> authenticateWithExchangeTokenHelper(request, assertionToken))); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(1024) .append(identityEndpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION); if (clientId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { LOGGER.warning("User assigned managed identities are not supported in the Service Fabric environment."); payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(connection, thumbprint, LOGGER); connection.setRequestMethod("GET"); if (identityHeader != null) { connection.setRequestProperty("Secret", identityHeader); } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * <p> * Specifying identity parameters will use the 2019-08-01 endpoint version. * Specifying MSI parameters will use the 2017-09-01 endpoint version. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the MSI secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(1024) .append(endpoint); payload.append("?resource="); payload.append(urlEncode(resource)); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, StandardCharsets.UTF_8.name())); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { if (headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&clientid="); } payload.append(urlEncode(clientId)); } if (resourceId != null) { if (endpointVersion.equals(MSI_ENDPOINT_VERSION) && headerValue == null) { LOGGER.warning("User assigned managed identities are not supported in the Cloud Shell environment."); } payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } try { URL url = getUrl(payload.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (IDENTITY_ENDPOINT_VERSION.equals(endpointVersion)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version=2018-02-01"); payload.append("&resource="); payload.append(urlEncode(resource)); if (clientId != null) { payload.append("&client_id="); payload.append(urlEncode(clientId)); } if (resourceId != null) { payload.append("&mi_res_id="); payload.append(urlEncode(resourceId)); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = TRAILING_FORWARD_SLASHES.matcher(options.getImdsAuthorityHost()).replaceAll("") + IdentityConstants.DEFAULT_IMDS_TOKENPATH; return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = getUrl(endpoint + "?" + payload); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); return SERIALIZER_ADAPTER.deserialize(connection.getInputStream(), MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw LOGGER.logExceptionAsError(new RuntimeException( "Could not connect to the url: " + url + ".", exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 403) { if (connection.getResponseMessage() .contains("A socket operation was attempted to an unreachable network")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "Managed Identity response was not in the expected format." + " See the inner exception for details.", new Exception(connection.getResponseMessage()))); } } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(ThreadLocalRandom.current().nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw LOGGER.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw LOGGER.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = getUrl(endpoint + "?api-version=2018-02-01"); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { LOGGER.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } /** * Get the configured identity client options. * * @return the client options. */ public IdentityClientOptions getIdentityClientOptions() { return options; } private boolean isADFSTenant() { return ADFS_TENANT.equals(this.tenantId); } Function<AppTokenProviderParameters, CompletableFuture<TokenProviderResult>> getWorkloadIdentityTokenProvider() { return appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = authenticateWithExchangeToken(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }; } }
This one does not work in Jackson either. As temporary solution, I may add ``` private resourceType; protected setResourceType(..); public getResourceType(); ``` directly to this class, which would shadow the `resourceType` var in superclass.
public FhirR4DomainResource(@JsonProperty(value = "resourceType") String resourceType) { super(resourceType); setResourceType("Fhir_R4_DomainResource"); }
setResourceType("Fhir_R4_DomainResource");
public FhirR4DomainResource(@JsonProperty(value = "resourceType") String resourceType) { super(resourceType); }
class FhirR4DomainResource extends FhirR4Resource { /* * Text summary of the resource, for human interpretation */ @Generated @JsonProperty(value = "text") private FhirR4Narrative text; /* * Contained, inline Resources */ @Generated @JsonProperty(value = "contained") private List<FhirR4Resource> contained; /* * Additional Content defined by implementations */ @Generated @JsonProperty(value = "extension") private List<FhirR4Extension> extension; /* * Extensions that cannot be ignored */ @Generated @JsonProperty(value = "modifierExtension") private List<FhirR4Extension> modifierExtension; /** * Creates an instance of FhirR4DomainResource class. * * @param resourceType the resourceType value to set. */ @Generated @JsonCreator /** * Get the text property: Text summary of the resource, for human interpretation. * * @return the text value. */ @Generated public FhirR4Narrative getText() { return this.text; } /** * Set the text property: Text summary of the resource, for human interpretation. * * @param text the text value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setText(FhirR4Narrative text) { this.text = text; return this; } /** * Get the contained property: Contained, inline Resources. * * @return the contained value. */ @Generated public List<FhirR4Resource> getContained() { return this.contained; } /** * Set the contained property: Contained, inline Resources. * * @param contained the contained value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setContained(List<FhirR4Resource> contained) { this.contained = contained; return this; } /** * Get the extension property: Additional Content defined by implementations. * * @return the extension value. */ @Generated public List<FhirR4Extension> getExtension() { return this.extension; } /** * Set the extension property: Additional Content defined by implementations. * * @param extension the extension value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setExtension(List<FhirR4Extension> extension) { this.extension = extension; return this; } /** * Get the modifierExtension property: Extensions that cannot be ignored. * * @return the modifierExtension value. */ @Generated public List<FhirR4Extension> getModifierExtension() { return this.modifierExtension; } /** * Set the modifierExtension property: Extensions that cannot be ignored. * * @param modifierExtension the modifierExtension value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setModifierExtension(List<FhirR4Extension> modifierExtension) { this.modifierExtension = modifierExtension; return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setId(String id) { super.setId(id); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setMeta(FhirR4Meta meta) { super.setMeta(meta); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setImplicitRules(String implicitRules) { super.setImplicitRules(implicitRules); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setLanguage(String language) { super.setLanguage(language); return this; } }
class FhirR4DomainResource extends FhirR4Resource { /* * Text summary of the resource, for human interpretation */ @Generated @JsonProperty(value = "text") private FhirR4Narrative text; /* * Contained, inline Resources */ @Generated @JsonProperty(value = "contained") private List<FhirR4Resource> contained; /* * Additional Content defined by implementations */ @Generated @JsonProperty(value = "extension") private List<FhirR4Extension> extension; /* * Extensions that cannot be ignored */ @Generated @JsonProperty(value = "modifierExtension") private List<FhirR4Extension> modifierExtension; /** * Creates an instance of FhirR4DomainResource class. * * @param resourceType the resourceType value to set. */ @Generated @JsonCreator /** * Get the text property: Text summary of the resource, for human interpretation. * * @return the text value. */ @Generated public FhirR4Narrative getText() { return this.text; } /** * Set the text property: Text summary of the resource, for human interpretation. * * @param text the text value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setText(FhirR4Narrative text) { this.text = text; return this; } /** * Get the contained property: Contained, inline Resources. * * @return the contained value. */ @Generated public List<FhirR4Resource> getContained() { return this.contained; } /** * Set the contained property: Contained, inline Resources. * * @param contained the contained value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setContained(List<FhirR4Resource> contained) { this.contained = contained; return this; } /** * Get the extension property: Additional Content defined by implementations. * * @return the extension value. */ @Generated public List<FhirR4Extension> getExtension() { return this.extension; } /** * Set the extension property: Additional Content defined by implementations. * * @param extension the extension value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setExtension(List<FhirR4Extension> extension) { this.extension = extension; return this; } /** * Get the modifierExtension property: Extensions that cannot be ignored. * * @return the modifierExtension value. */ @Generated public List<FhirR4Extension> getModifierExtension() { return this.modifierExtension; } /** * Set the modifierExtension property: Extensions that cannot be ignored. * * @param modifierExtension the modifierExtension value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setModifierExtension(List<FhirR4Extension> modifierExtension) { this.modifierExtension = modifierExtension; return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setId(String id) { super.setId(id); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setMeta(FhirR4Meta meta) { super.setMeta(meta); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setImplicitRules(String implicitRules) { super.setImplicitRules(implicitRules); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setLanguage(String language) { super.setLanguage(language); return this; } /* * resourceType */ @Generated @JsonTypeId @JsonProperty(value = "resourceType") private String resourceType; /** * Get the resourceType property: resourceType. * * @return the resourceType value. */ @Generated @Override public String getResourceType() { return this.resourceType; } }
https://github.com/Azure/autorest.java/pull/2639 seems mitigated this as well
public FhirR4DomainResource(@JsonProperty(value = "resourceType") String resourceType) { super(resourceType); setResourceType("Fhir_R4_DomainResource"); }
setResourceType("Fhir_R4_DomainResource");
public FhirR4DomainResource(@JsonProperty(value = "resourceType") String resourceType) { super(resourceType); }
class FhirR4DomainResource extends FhirR4Resource { /* * Text summary of the resource, for human interpretation */ @Generated @JsonProperty(value = "text") private FhirR4Narrative text; /* * Contained, inline Resources */ @Generated @JsonProperty(value = "contained") private List<FhirR4Resource> contained; /* * Additional Content defined by implementations */ @Generated @JsonProperty(value = "extension") private List<FhirR4Extension> extension; /* * Extensions that cannot be ignored */ @Generated @JsonProperty(value = "modifierExtension") private List<FhirR4Extension> modifierExtension; /** * Creates an instance of FhirR4DomainResource class. * * @param resourceType the resourceType value to set. */ @Generated @JsonCreator /** * Get the text property: Text summary of the resource, for human interpretation. * * @return the text value. */ @Generated public FhirR4Narrative getText() { return this.text; } /** * Set the text property: Text summary of the resource, for human interpretation. * * @param text the text value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setText(FhirR4Narrative text) { this.text = text; return this; } /** * Get the contained property: Contained, inline Resources. * * @return the contained value. */ @Generated public List<FhirR4Resource> getContained() { return this.contained; } /** * Set the contained property: Contained, inline Resources. * * @param contained the contained value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setContained(List<FhirR4Resource> contained) { this.contained = contained; return this; } /** * Get the extension property: Additional Content defined by implementations. * * @return the extension value. */ @Generated public List<FhirR4Extension> getExtension() { return this.extension; } /** * Set the extension property: Additional Content defined by implementations. * * @param extension the extension value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setExtension(List<FhirR4Extension> extension) { this.extension = extension; return this; } /** * Get the modifierExtension property: Extensions that cannot be ignored. * * @return the modifierExtension value. */ @Generated public List<FhirR4Extension> getModifierExtension() { return this.modifierExtension; } /** * Set the modifierExtension property: Extensions that cannot be ignored. * * @param modifierExtension the modifierExtension value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setModifierExtension(List<FhirR4Extension> modifierExtension) { this.modifierExtension = modifierExtension; return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setId(String id) { super.setId(id); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setMeta(FhirR4Meta meta) { super.setMeta(meta); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setImplicitRules(String implicitRules) { super.setImplicitRules(implicitRules); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setLanguage(String language) { super.setLanguage(language); return this; } }
class FhirR4DomainResource extends FhirR4Resource { /* * Text summary of the resource, for human interpretation */ @Generated @JsonProperty(value = "text") private FhirR4Narrative text; /* * Contained, inline Resources */ @Generated @JsonProperty(value = "contained") private List<FhirR4Resource> contained; /* * Additional Content defined by implementations */ @Generated @JsonProperty(value = "extension") private List<FhirR4Extension> extension; /* * Extensions that cannot be ignored */ @Generated @JsonProperty(value = "modifierExtension") private List<FhirR4Extension> modifierExtension; /** * Creates an instance of FhirR4DomainResource class. * * @param resourceType the resourceType value to set. */ @Generated @JsonCreator /** * Get the text property: Text summary of the resource, for human interpretation. * * @return the text value. */ @Generated public FhirR4Narrative getText() { return this.text; } /** * Set the text property: Text summary of the resource, for human interpretation. * * @param text the text value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setText(FhirR4Narrative text) { this.text = text; return this; } /** * Get the contained property: Contained, inline Resources. * * @return the contained value. */ @Generated public List<FhirR4Resource> getContained() { return this.contained; } /** * Set the contained property: Contained, inline Resources. * * @param contained the contained value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setContained(List<FhirR4Resource> contained) { this.contained = contained; return this; } /** * Get the extension property: Additional Content defined by implementations. * * @return the extension value. */ @Generated public List<FhirR4Extension> getExtension() { return this.extension; } /** * Set the extension property: Additional Content defined by implementations. * * @param extension the extension value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setExtension(List<FhirR4Extension> extension) { this.extension = extension; return this; } /** * Get the modifierExtension property: Extensions that cannot be ignored. * * @return the modifierExtension value. */ @Generated public List<FhirR4Extension> getModifierExtension() { return this.modifierExtension; } /** * Set the modifierExtension property: Extensions that cannot be ignored. * * @param modifierExtension the modifierExtension value to set. * @return the FhirR4DomainResource object itself. */ @Generated public FhirR4DomainResource setModifierExtension(List<FhirR4Extension> modifierExtension) { this.modifierExtension = modifierExtension; return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setId(String id) { super.setId(id); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setMeta(FhirR4Meta meta) { super.setMeta(meta); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setImplicitRules(String implicitRules) { super.setImplicitRules(implicitRules); return this; } /** * {@inheritDoc} */ @Generated @Override public FhirR4DomainResource setLanguage(String language) { super.setLanguage(language); return this; } /* * resourceType */ @Generated @JsonTypeId @JsonProperty(value = "resourceType") private String resourceType; /** * Get the resourceType property: resourceType. * * @return the resourceType value. */ @Generated @Override public String getResourceType() { return this.resourceType; } }
We should not convert each time this method is called. This should be done only once.
public List<Float> getEmbedding() { return convertToFloatList(embedding.toString()); }
return convertToFloatList(embedding.toString());
public List<Float> getEmbedding() { return convertBase64ToFloatList(embeddingBase64); }
class EmbeddingItem { /* * List of embeddings value for the input prompt. These represent a measurement of the * vector-based relatedness of the provided input. */ @JsonProperty(value = "embedding") private BinaryData embedding; /** * Get the embedding property: List of embeddings value for the input prompt. These represent a measurement of the * vector-based relatedness of the provided input. * * @return the embedding value. */ /** * Get the embedding property: List of embeddings value in base64 format for the input prompt. * * @return the embedding base64 encoded string. */ public String getEmbeddingString() { return embedding.toString(); } /* * Index of the prompt to which the EmbeddingItem corresponds. */ @Generated @JsonProperty(value = "index") private int promptIndex; /** * Get the promptIndex property: Index of the prompt to which the EmbeddingItem corresponds. * * @return the promptIndex value. */ @Generated public int getPromptIndex() { return this.promptIndex; } /** * Creates an instance of EmbeddingItem class. * * @param embedding the embedding value to set. * @param promptIndex the promptIndex value to set. */ @JsonCreator private EmbeddingItem(@JsonProperty(value = "embedding") BinaryData embedding, @JsonProperty(value = "index") int promptIndex) { this.embedding = embedding; this.promptIndex = promptIndex; } private List<Float> convertToFloatList(String embedding) { byte[] bytes = Base64.getDecoder().decode(embedding); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); FloatBuffer floatBuffer = byteBuffer.asFloatBuffer(); List<Float> floatList = new ArrayList<>(floatBuffer.remaining()); while (floatBuffer.hasRemaining()) { floatList.add(floatBuffer.get()); } return floatList; } }
class EmbeddingItem { /* * List of embeddings value for the input prompt. These represent a measurement of the * vector-based relatedness of the provided input. */ @JsonProperty(value = "embedding") private BinaryData embedding; private final String embeddingBase64; /** * Get the embedding property: List of embeddings value for the input prompt. These represent a measurement of the * vector-based relatedness of the provided input. * * @return the embedding value. */ /** * Get the embedding property: List of embeddings value in base64 format for the input prompt. * * @return the embedding base64 encoded string. */ public String getEmbeddingAsString() { return embeddingBase64; } /* * Index of the prompt to which the EmbeddingItem corresponds. */ @Generated @JsonProperty(value = "index") private int promptIndex; /** * Get the promptIndex property: Index of the prompt to which the EmbeddingItem corresponds. * * @return the promptIndex value. */ @Generated public int getPromptIndex() { return this.promptIndex; } /** * Creates an instance of EmbeddingItem class. * * @param embedding the embedding value to set. * @param promptIndex the promptIndex value to set. */ @JsonCreator private EmbeddingItem(@JsonProperty(value = "embedding") BinaryData embedding, @JsonProperty(value = "index") int promptIndex) { this.embedding = embedding; this.promptIndex = promptIndex; embeddingBase64 = embedding.toString(); } }
what purpose would that have? That test would be flaky by design - unless you use a high enough iteration count to force hitting each of the two code paths being hit?
public void onlyCustomLoggerAlwaysSampledOut() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(0); }
.sampleDiagnostics(0)
public void onlyCustomLoggerAlwaysSampledOut() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(0); }
class CosmosDiagnosticsE2ETest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().configure( JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true ); private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosDiagnosticsE2ETest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"fast", "emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.client).isNull(); } @AfterClass(groups = {"fast", "emulator"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { clientSnapshot.close(); } } @DataProvider public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Delete }, { OperationType.Query } }; } public String resolveTestNameSuffix(Object[] row) { return ""; } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomDiagnosticsHandler() { CapturingDiagnosticsHandler capturingHandler = new CapturingDiagnosticsHandler(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingHandler) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); assertThat(capturingHandler.getDiagnosticsContexts()).hasSize(1); CosmosDiagnosticsContext ctx = capturingHandler.getDiagnosticsContexts().get(0); assertThat(ctx).isNotNull(); assertThat(ctx.isCompleted()).isEqualTo(true); assertThat(ctx.getDiagnostics()).isNotEmpty(); assertThat(ctx.getContainerName()).isEqualTo(container.getId()); assertThat(ctx.getDatabaseName()).isEqualTo(container.asyncContainer.getDatabase().getId()); assertThat(ctx.getDuration()).isNotNull(); assertThat(ctx.getDuration()).isGreaterThan(Duration.ZERO); assertThat(ctx.getFinalError()).isNull(); assertThat(ctx.getMaxItemCount()).isNull(); if (this.getClientBuilder().isContentResponseOnWriteEnabled()) { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isGreaterThan(0); } else { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isEqualTo(0); } assertThat(ctx.getOperationType()).isEqualTo(OperationType.Create.toString()); assertThat(ctx.getOperationTypeInternal()).isEqualTo(OperationType.Create); assertThat(ctx.getResourceType()).isEqualTo(ResourceType.Document.toString()); assertThat(ctx.getResourceTypeInternal()).isEqualTo(ResourceType.Document); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyDefaultLogger() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerWithCustomConfig() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerAlwaysSampledOut() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomLoggerWithCustomConfig() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) ); CosmosContainer container = this.getContainer(builder); String id = UUID.randomUUID().toString(); ObjectNode doc = getDocumentDefinition(id); CosmosDiagnostics diagnostics = executeDocumentOperation(container, OperationType.Create, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); diagnostics = executeDocumentOperation(container, OperationType.Query, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(2); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerAndMetrics() { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); } @Test(groups = { "fast", "emulator" }, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void delayedSampling(OperationType operationType) { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientTelemetryConfig clientTelemetryCfg = new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingLogger) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(clientTelemetryCfg); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); String id = UUID.randomUUID().toString(); ObjectNode newItem = getDocumentDefinition(id); container.createItem(newItem); clientTelemetryCfg.sampleDiagnostics(0.25); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeBefore = capturingLogger.getLoggedMessages().size(); clientTelemetryCfg.sampleDiagnostics(0); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore).isEqualTo(loggedMessageSizeAfter); clientTelemetryCfg.sampleDiagnostics(1); executeDocumentOperation(container, operationType, id, newItem); loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore + 1).isEqualTo(loggedMessageSizeAfter); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerWithLegacyOpenTelemetryTraces() { System.setProperty("COSMOS.USE_LEGACY_TRACING", "true"); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); System.setProperty("COSMOS.USE_LEGACY_TRACING", "false"); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void nullPointerDiagnosticsHandler() { NullPointerDiagnosticsHandle capturingHandler = new NullPointerDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); executeTestCase(container); assertThat(systemExited.get()).isFalse(); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandler() throws InterruptedException { System.setProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR", "false"); try { OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); Mono.just(this) .doOnNext(t -> executeTestCase(container)) .subscribeOn(Schedulers.parallel()) .subscribe(); Thread.sleep(2000); assertThat(systemExited.get()).isFalse(); } finally { System.clearProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandlerWithErrorMapper() throws JsonProcessingException { DiagnosticsProviderJvmFatalErrorMapper .getMapper() .registerFatalErrorMapper((error) -> new NullPointerException("test")); OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(ResourceType.Document, OperationType.Create); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); try { executeTestCase(container); fail("should fail with RuntimeException"); } catch (RuntimeException e) { assertThat(e.getCause() instanceof NullPointerException).isTrue(); assertThat(systemExited.get()).isFalse(); } CosmosDiagnostics cosmosDiagnostics = container.upsertItem(getDocumentDefinition(UUID.randomUUID().toString())).getDiagnostics(); ObjectNode cosmosDiagnosticsNode = (ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString()); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount")).isNotNull(); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount").asLong()).isGreaterThan(0); } private CosmosItemResponse<ObjectNode> executeTestCase(CosmosContainer container) { String id = UUID.randomUUID().toString(); CosmosItemResponse<ObjectNode> response = container.createItem( getDocumentDefinition(id), new PartitionKey(id), new CosmosItemRequestOptions()); assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(201); return response; } private ObjectNode getDocumentDefinition(String documentId) { String json = String.format( "{ \"id\": \"%s\", \"mypk\": \"%s\" }", documentId, documentId); try { return OBJECT_MAPPER.readValue(json, ObjectNode.class); } catch (JsonProcessingException jsonError) { fail("No json processing error expected", jsonError); throw new IllegalStateException("No json processing error expected", jsonError); } } private CosmosContainer getContainer(CosmosClientBuilder builder) { CosmosClient oldClient = this.client; if (oldClient != null) { oldClient.close(); } assertThat(builder).isNotNull(); this.client = builder.buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); return this.client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } private CosmosDiagnostics executeDocumentOperation( CosmosContainer cosmosContainer, OperationType operationType, String createdItemId, ObjectNode createdItem) { final AtomicReference<CosmosDiagnostics> diagnostics = new AtomicReference<>(null); switch (operationType) { case Query: String query = String.format("SELECT * from c"); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); queryRequestOptions.setFeedRange(FeedRange.forLogicalPartition(new PartitionKey(createdItemId))); Iterable<FeedResponse<JsonNode>> queryResults = cosmosContainer.queryItems(query, queryRequestOptions, JsonNode.class).iterableByPage(); queryResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case ReadFeed: CosmosChangeFeedRequestOptions changeFeedRequestOptions = CosmosChangeFeedRequestOptions .createForProcessingFromBeginning(FeedRange.forFullRange()); Iterable<FeedResponse<JsonNode>> changeFeedResults = cosmosContainer.queryChangeFeed(changeFeedRequestOptions, JsonNode.class).iterableByPage(); changeFeedResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case Read: CosmosItemResponse<JsonNode> readResponse = cosmosContainer .readItem(createdItemId, new PartitionKey(createdItemId), JsonNode.class); diagnostics.set(readResponse.getDiagnostics()); break; case Replace: CosmosItemResponse<JsonNode> replaceResponse = cosmosContainer .replaceItem(createdItem, createdItemId, new PartitionKey(createdItemId), new CosmosItemRequestOptions()); diagnostics.set(replaceResponse.getDiagnostics()); break; case Delete: try { CosmosItemResponse<Object> deleteResponse = cosmosContainer.deleteItem(getDocumentDefinition(UUID.randomUUID().toString()), new CosmosItemRequestOptions()); diagnostics.set(deleteResponse.getDiagnostics()); } catch (CosmosException e) { if (!Exceptions.isNotFound(e)) { throw e; } } break; case Create: CosmosItemResponse<JsonNode> createResponse = cosmosContainer.createItem(getDocumentDefinition(UUID.randomUUID().toString())); diagnostics.set(createResponse.getDiagnostics()); break; default: throw new IllegalArgumentException("The operation type is not supported"); } return diagnostics.get(); } private static class CapturingDiagnosticsHandler implements CosmosDiagnosticsHandler { private final ArrayList<CosmosDiagnosticsContext> diagnosticsContexts = new ArrayList<>(); @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { diagnosticsContexts.add(diagnosticsContext); } public List<CosmosDiagnosticsContext> getDiagnosticsContexts() { return this.diagnosticsContexts; } } private static class CapturingLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public CapturingLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {} - json: {}", ctx, ctx != null ? ctx.toJson() : "n/a"); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); logger.info(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class ConsoleOutLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public ConsoleOutLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {}", ctx); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); System.out.println(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class NullPointerDiagnosticsHandle implements CosmosDiagnosticsHandler { @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { throw new NullPointerException("NullPointerDiagnosticsHandle"); } } private static class OOMDiagnosticsHandle implements CosmosDiagnosticsHandler { private ResourceType resourceType; private OperationType operationType; private final boolean oomLimitByResourceAndOperationType; public OOMDiagnosticsHandle(ResourceType resourceType, OperationType operationType) { this.resourceType = resourceType; this.operationType = operationType; this.oomLimitByResourceAndOperationType = true; } public OOMDiagnosticsHandle() { this.oomLimitByResourceAndOperationType = false; } @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { if (this.oomLimitByResourceAndOperationType) { if (diagnosticsContext.getOperationType() == this.operationType.toString() && diagnosticsContext.getResourceType() == this.resourceType.toString()) { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } else { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } } }
class CosmosDiagnosticsE2ETest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().configure( JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true ); private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosDiagnosticsE2ETest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"fast", "emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.client).isNull(); } @AfterClass(groups = {"fast", "emulator"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { clientSnapshot.close(); } } @DataProvider public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Delete }, { OperationType.Query } }; } public String resolveTestNameSuffix(Object[] row) { return ""; } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomDiagnosticsHandler() { CapturingDiagnosticsHandler capturingHandler = new CapturingDiagnosticsHandler(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingHandler) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); assertThat(capturingHandler.getDiagnosticsContexts()).hasSize(1); CosmosDiagnosticsContext ctx = capturingHandler.getDiagnosticsContexts().get(0); assertThat(ctx).isNotNull(); assertThat(ctx.isCompleted()).isEqualTo(true); assertThat(ctx.getDiagnostics()).isNotEmpty(); assertThat(ctx.getContainerName()).isEqualTo(container.getId()); assertThat(ctx.getDatabaseName()).isEqualTo(container.asyncContainer.getDatabase().getId()); assertThat(ctx.getDuration()).isNotNull(); assertThat(ctx.getDuration()).isGreaterThan(Duration.ZERO); assertThat(ctx.getFinalError()).isNull(); assertThat(ctx.getMaxItemCount()).isNull(); if (this.getClientBuilder().isContentResponseOnWriteEnabled()) { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isGreaterThan(0); } else { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isEqualTo(0); } assertThat(ctx.getOperationType()).isEqualTo(OperationType.Create.toString()); assertThat(ctx.getOperationTypeInternal()).isEqualTo(OperationType.Create); assertThat(ctx.getResourceType()).isEqualTo(ResourceType.Document.toString()); assertThat(ctx.getResourceTypeInternal()).isEqualTo(ResourceType.Document); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyDefaultLogger() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerWithCustomConfig() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerAlwaysSampledOut() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomLoggerWithCustomConfig() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) ); CosmosContainer container = this.getContainer(builder); String id = UUID.randomUUID().toString(); ObjectNode doc = getDocumentDefinition(id); CosmosDiagnostics diagnostics = executeDocumentOperation(container, OperationType.Create, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); diagnostics = executeDocumentOperation(container, OperationType.Query, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(2); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerAndMetrics() { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); } @Test(groups = { "fast", "emulator" }, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void delayedSampling(OperationType operationType) { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientTelemetryConfig clientTelemetryCfg = new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingLogger) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(clientTelemetryCfg); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); String id = UUID.randomUUID().toString(); ObjectNode newItem = getDocumentDefinition(id); container.createItem(newItem); clientTelemetryCfg.sampleDiagnostics(0.25); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeBefore = capturingLogger.getLoggedMessages().size(); clientTelemetryCfg.sampleDiagnostics(0); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore).isEqualTo(loggedMessageSizeAfter); clientTelemetryCfg.sampleDiagnostics(1); executeDocumentOperation(container, operationType, id, newItem); loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore + 1).isEqualTo(loggedMessageSizeAfter); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerWithLegacyOpenTelemetryTraces() { System.setProperty("COSMOS.USE_LEGACY_TRACING", "true"); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); System.setProperty("COSMOS.USE_LEGACY_TRACING", "false"); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void nullPointerDiagnosticsHandler() { NullPointerDiagnosticsHandle capturingHandler = new NullPointerDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); executeTestCase(container); assertThat(systemExited.get()).isFalse(); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandler() throws InterruptedException { System.setProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR", "false"); try { OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); Mono.just(this) .doOnNext(t -> executeTestCase(container)) .subscribeOn(Schedulers.parallel()) .subscribe(); Thread.sleep(2000); assertThat(systemExited.get()).isFalse(); } finally { System.clearProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandlerWithErrorMapper() throws JsonProcessingException { DiagnosticsProviderJvmFatalErrorMapper .getMapper() .registerFatalErrorMapper((error) -> new NullPointerException("test")); OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(ResourceType.Document, OperationType.Create); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); try { executeTestCase(container); fail("should fail with RuntimeException"); } catch (RuntimeException e) { assertThat(e.getCause() instanceof NullPointerException).isTrue(); assertThat(systemExited.get()).isFalse(); } CosmosDiagnostics cosmosDiagnostics = container.upsertItem(getDocumentDefinition(UUID.randomUUID().toString())).getDiagnostics(); ObjectNode cosmosDiagnosticsNode = (ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString()); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount")).isNotNull(); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount").asLong()).isGreaterThan(0); } private CosmosItemResponse<ObjectNode> executeTestCase(CosmosContainer container) { String id = UUID.randomUUID().toString(); CosmosItemResponse<ObjectNode> response = container.createItem( getDocumentDefinition(id), new PartitionKey(id), new CosmosItemRequestOptions()); assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(201); return response; } private ObjectNode getDocumentDefinition(String documentId) { String json = String.format( "{ \"id\": \"%s\", \"mypk\": \"%s\" }", documentId, documentId); try { return OBJECT_MAPPER.readValue(json, ObjectNode.class); } catch (JsonProcessingException jsonError) { fail("No json processing error expected", jsonError); throw new IllegalStateException("No json processing error expected", jsonError); } } private CosmosContainer getContainer(CosmosClientBuilder builder) { CosmosClient oldClient = this.client; if (oldClient != null) { oldClient.close(); } assertThat(builder).isNotNull(); this.client = builder.buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); return this.client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } private CosmosDiagnostics executeDocumentOperation( CosmosContainer cosmosContainer, OperationType operationType, String createdItemId, ObjectNode createdItem) { final AtomicReference<CosmosDiagnostics> diagnostics = new AtomicReference<>(null); switch (operationType) { case Query: String query = String.format("SELECT * from c"); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); queryRequestOptions.setFeedRange(FeedRange.forLogicalPartition(new PartitionKey(createdItemId))); Iterable<FeedResponse<JsonNode>> queryResults = cosmosContainer.queryItems(query, queryRequestOptions, JsonNode.class).iterableByPage(); queryResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case ReadFeed: CosmosChangeFeedRequestOptions changeFeedRequestOptions = CosmosChangeFeedRequestOptions .createForProcessingFromBeginning(FeedRange.forFullRange()); Iterable<FeedResponse<JsonNode>> changeFeedResults = cosmosContainer.queryChangeFeed(changeFeedRequestOptions, JsonNode.class).iterableByPage(); changeFeedResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case Read: CosmosItemResponse<JsonNode> readResponse = cosmosContainer .readItem(createdItemId, new PartitionKey(createdItemId), JsonNode.class); diagnostics.set(readResponse.getDiagnostics()); break; case Replace: CosmosItemResponse<JsonNode> replaceResponse = cosmosContainer .replaceItem(createdItem, createdItemId, new PartitionKey(createdItemId), new CosmosItemRequestOptions()); diagnostics.set(replaceResponse.getDiagnostics()); break; case Delete: try { CosmosItemResponse<Object> deleteResponse = cosmosContainer.deleteItem(getDocumentDefinition(UUID.randomUUID().toString()), new CosmosItemRequestOptions()); diagnostics.set(deleteResponse.getDiagnostics()); } catch (CosmosException e) { if (!Exceptions.isNotFound(e)) { throw e; } } break; case Create: CosmosItemResponse<JsonNode> createResponse = cosmosContainer.createItem(getDocumentDefinition(UUID.randomUUID().toString())); diagnostics.set(createResponse.getDiagnostics()); break; default: throw new IllegalArgumentException("The operation type is not supported"); } return diagnostics.get(); } private static class CapturingDiagnosticsHandler implements CosmosDiagnosticsHandler { private final ArrayList<CosmosDiagnosticsContext> diagnosticsContexts = new ArrayList<>(); @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { diagnosticsContexts.add(diagnosticsContext); } public List<CosmosDiagnosticsContext> getDiagnosticsContexts() { return this.diagnosticsContexts; } } private static class CapturingLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public CapturingLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {} - json: {}", ctx, ctx != null ? ctx.toJson() : "n/a"); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); logger.info(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class ConsoleOutLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public ConsoleOutLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {}", ctx); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); System.out.println(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class NullPointerDiagnosticsHandle implements CosmosDiagnosticsHandler { @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { throw new NullPointerException("NullPointerDiagnosticsHandle"); } } private static class OOMDiagnosticsHandle implements CosmosDiagnosticsHandler { private ResourceType resourceType; private OperationType operationType; private final boolean oomLimitByResourceAndOperationType; public OOMDiagnosticsHandle(ResourceType resourceType, OperationType operationType) { this.resourceType = resourceType; this.operationType = operationType; this.oomLimitByResourceAndOperationType = true; } public OOMDiagnosticsHandle() { this.oomLimitByResourceAndOperationType = false; } @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { if (this.oomLimitByResourceAndOperationType) { if (diagnosticsContext.getOperationType() == this.operationType.toString() && diagnosticsContext.getResourceType() == this.resourceType.toString()) { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } else { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } } }
Can we also add a test case where we actually sampleDiagnostics with value > 0 and < 1?
public void onlyCustomLoggerAlwaysSampledOut() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(0); }
.sampleDiagnostics(0)
public void onlyCustomLoggerAlwaysSampledOut() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(0); }
class CosmosDiagnosticsE2ETest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().configure( JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true ); private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosDiagnosticsE2ETest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"fast", "emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.client).isNull(); } @AfterClass(groups = {"fast", "emulator"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { clientSnapshot.close(); } } @DataProvider public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Delete }, { OperationType.Query } }; } public String resolveTestNameSuffix(Object[] row) { return ""; } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomDiagnosticsHandler() { CapturingDiagnosticsHandler capturingHandler = new CapturingDiagnosticsHandler(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingHandler) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); assertThat(capturingHandler.getDiagnosticsContexts()).hasSize(1); CosmosDiagnosticsContext ctx = capturingHandler.getDiagnosticsContexts().get(0); assertThat(ctx).isNotNull(); assertThat(ctx.isCompleted()).isEqualTo(true); assertThat(ctx.getDiagnostics()).isNotEmpty(); assertThat(ctx.getContainerName()).isEqualTo(container.getId()); assertThat(ctx.getDatabaseName()).isEqualTo(container.asyncContainer.getDatabase().getId()); assertThat(ctx.getDuration()).isNotNull(); assertThat(ctx.getDuration()).isGreaterThan(Duration.ZERO); assertThat(ctx.getFinalError()).isNull(); assertThat(ctx.getMaxItemCount()).isNull(); if (this.getClientBuilder().isContentResponseOnWriteEnabled()) { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isGreaterThan(0); } else { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isEqualTo(0); } assertThat(ctx.getOperationType()).isEqualTo(OperationType.Create.toString()); assertThat(ctx.getOperationTypeInternal()).isEqualTo(OperationType.Create); assertThat(ctx.getResourceType()).isEqualTo(ResourceType.Document.toString()); assertThat(ctx.getResourceTypeInternal()).isEqualTo(ResourceType.Document); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyDefaultLogger() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerWithCustomConfig() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerAlwaysSampledOut() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomLoggerWithCustomConfig() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) ); CosmosContainer container = this.getContainer(builder); String id = UUID.randomUUID().toString(); ObjectNode doc = getDocumentDefinition(id); CosmosDiagnostics diagnostics = executeDocumentOperation(container, OperationType.Create, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); diagnostics = executeDocumentOperation(container, OperationType.Query, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(2); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerAndMetrics() { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); } @Test(groups = { "fast", "emulator" }, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void delayedSampling(OperationType operationType) { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientTelemetryConfig clientTelemetryCfg = new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingLogger) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(clientTelemetryCfg); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); String id = UUID.randomUUID().toString(); ObjectNode newItem = getDocumentDefinition(id); container.createItem(newItem); clientTelemetryCfg.sampleDiagnostics(0.25); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeBefore = capturingLogger.getLoggedMessages().size(); clientTelemetryCfg.sampleDiagnostics(0); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore).isEqualTo(loggedMessageSizeAfter); clientTelemetryCfg.sampleDiagnostics(1); executeDocumentOperation(container, operationType, id, newItem); loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore + 1).isEqualTo(loggedMessageSizeAfter); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerWithLegacyOpenTelemetryTraces() { System.setProperty("COSMOS.USE_LEGACY_TRACING", "true"); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); System.setProperty("COSMOS.USE_LEGACY_TRACING", "false"); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void nullPointerDiagnosticsHandler() { NullPointerDiagnosticsHandle capturingHandler = new NullPointerDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); executeTestCase(container); assertThat(systemExited.get()).isFalse(); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandler() throws InterruptedException { System.setProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR", "false"); try { OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); Mono.just(this) .doOnNext(t -> executeTestCase(container)) .subscribeOn(Schedulers.parallel()) .subscribe(); Thread.sleep(2000); assertThat(systemExited.get()).isFalse(); } finally { System.clearProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandlerWithErrorMapper() throws JsonProcessingException { DiagnosticsProviderJvmFatalErrorMapper .getMapper() .registerFatalErrorMapper((error) -> new NullPointerException("test")); OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(ResourceType.Document, OperationType.Create); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); try { executeTestCase(container); fail("should fail with RuntimeException"); } catch (RuntimeException e) { assertThat(e.getCause() instanceof NullPointerException).isTrue(); assertThat(systemExited.get()).isFalse(); } CosmosDiagnostics cosmosDiagnostics = container.upsertItem(getDocumentDefinition(UUID.randomUUID().toString())).getDiagnostics(); ObjectNode cosmosDiagnosticsNode = (ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString()); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount")).isNotNull(); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount").asLong()).isGreaterThan(0); } private CosmosItemResponse<ObjectNode> executeTestCase(CosmosContainer container) { String id = UUID.randomUUID().toString(); CosmosItemResponse<ObjectNode> response = container.createItem( getDocumentDefinition(id), new PartitionKey(id), new CosmosItemRequestOptions()); assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(201); return response; } private ObjectNode getDocumentDefinition(String documentId) { String json = String.format( "{ \"id\": \"%s\", \"mypk\": \"%s\" }", documentId, documentId); try { return OBJECT_MAPPER.readValue(json, ObjectNode.class); } catch (JsonProcessingException jsonError) { fail("No json processing error expected", jsonError); throw new IllegalStateException("No json processing error expected", jsonError); } } private CosmosContainer getContainer(CosmosClientBuilder builder) { CosmosClient oldClient = this.client; if (oldClient != null) { oldClient.close(); } assertThat(builder).isNotNull(); this.client = builder.buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); return this.client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } private CosmosDiagnostics executeDocumentOperation( CosmosContainer cosmosContainer, OperationType operationType, String createdItemId, ObjectNode createdItem) { final AtomicReference<CosmosDiagnostics> diagnostics = new AtomicReference<>(null); switch (operationType) { case Query: String query = String.format("SELECT * from c"); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); queryRequestOptions.setFeedRange(FeedRange.forLogicalPartition(new PartitionKey(createdItemId))); Iterable<FeedResponse<JsonNode>> queryResults = cosmosContainer.queryItems(query, queryRequestOptions, JsonNode.class).iterableByPage(); queryResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case ReadFeed: CosmosChangeFeedRequestOptions changeFeedRequestOptions = CosmosChangeFeedRequestOptions .createForProcessingFromBeginning(FeedRange.forFullRange()); Iterable<FeedResponse<JsonNode>> changeFeedResults = cosmosContainer.queryChangeFeed(changeFeedRequestOptions, JsonNode.class).iterableByPage(); changeFeedResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case Read: CosmosItemResponse<JsonNode> readResponse = cosmosContainer .readItem(createdItemId, new PartitionKey(createdItemId), JsonNode.class); diagnostics.set(readResponse.getDiagnostics()); break; case Replace: CosmosItemResponse<JsonNode> replaceResponse = cosmosContainer .replaceItem(createdItem, createdItemId, new PartitionKey(createdItemId), new CosmosItemRequestOptions()); diagnostics.set(replaceResponse.getDiagnostics()); break; case Delete: try { CosmosItemResponse<Object> deleteResponse = cosmosContainer.deleteItem(getDocumentDefinition(UUID.randomUUID().toString()), new CosmosItemRequestOptions()); diagnostics.set(deleteResponse.getDiagnostics()); } catch (CosmosException e) { if (!Exceptions.isNotFound(e)) { throw e; } } break; case Create: CosmosItemResponse<JsonNode> createResponse = cosmosContainer.createItem(getDocumentDefinition(UUID.randomUUID().toString())); diagnostics.set(createResponse.getDiagnostics()); break; default: throw new IllegalArgumentException("The operation type is not supported"); } return diagnostics.get(); } private static class CapturingDiagnosticsHandler implements CosmosDiagnosticsHandler { private final ArrayList<CosmosDiagnosticsContext> diagnosticsContexts = new ArrayList<>(); @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { diagnosticsContexts.add(diagnosticsContext); } public List<CosmosDiagnosticsContext> getDiagnosticsContexts() { return this.diagnosticsContexts; } } private static class CapturingLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public CapturingLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {} - json: {}", ctx, ctx != null ? ctx.toJson() : "n/a"); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); logger.info(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class ConsoleOutLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public ConsoleOutLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {}", ctx); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); System.out.println(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class NullPointerDiagnosticsHandle implements CosmosDiagnosticsHandler { @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { throw new NullPointerException("NullPointerDiagnosticsHandle"); } } private static class OOMDiagnosticsHandle implements CosmosDiagnosticsHandler { private ResourceType resourceType; private OperationType operationType; private final boolean oomLimitByResourceAndOperationType; public OOMDiagnosticsHandle(ResourceType resourceType, OperationType operationType) { this.resourceType = resourceType; this.operationType = operationType; this.oomLimitByResourceAndOperationType = true; } public OOMDiagnosticsHandle() { this.oomLimitByResourceAndOperationType = false; } @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { if (this.oomLimitByResourceAndOperationType) { if (diagnosticsContext.getOperationType() == this.operationType.toString() && diagnosticsContext.getResourceType() == this.resourceType.toString()) { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } else { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } } }
class CosmosDiagnosticsE2ETest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().configure( JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true ); private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosDiagnosticsE2ETest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"fast", "emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.client).isNull(); } @AfterClass(groups = {"fast", "emulator"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { clientSnapshot.close(); } } @DataProvider public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Delete }, { OperationType.Query } }; } public String resolveTestNameSuffix(Object[] row) { return ""; } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomDiagnosticsHandler() { CapturingDiagnosticsHandler capturingHandler = new CapturingDiagnosticsHandler(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingHandler) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); assertThat(capturingHandler.getDiagnosticsContexts()).hasSize(1); CosmosDiagnosticsContext ctx = capturingHandler.getDiagnosticsContexts().get(0); assertThat(ctx).isNotNull(); assertThat(ctx.isCompleted()).isEqualTo(true); assertThat(ctx.getDiagnostics()).isNotEmpty(); assertThat(ctx.getContainerName()).isEqualTo(container.getId()); assertThat(ctx.getDatabaseName()).isEqualTo(container.asyncContainer.getDatabase().getId()); assertThat(ctx.getDuration()).isNotNull(); assertThat(ctx.getDuration()).isGreaterThan(Duration.ZERO); assertThat(ctx.getFinalError()).isNull(); assertThat(ctx.getMaxItemCount()).isNull(); if (this.getClientBuilder().isContentResponseOnWriteEnabled()) { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isGreaterThan(0); } else { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isEqualTo(0); } assertThat(ctx.getOperationType()).isEqualTo(OperationType.Create.toString()); assertThat(ctx.getOperationTypeInternal()).isEqualTo(OperationType.Create); assertThat(ctx.getResourceType()).isEqualTo(ResourceType.Document.toString()); assertThat(ctx.getResourceTypeInternal()).isEqualTo(ResourceType.Document); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyDefaultLogger() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerWithCustomConfig() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerAlwaysSampledOut() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomLoggerWithCustomConfig() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) ); CosmosContainer container = this.getContainer(builder); String id = UUID.randomUUID().toString(); ObjectNode doc = getDocumentDefinition(id); CosmosDiagnostics diagnostics = executeDocumentOperation(container, OperationType.Create, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); diagnostics = executeDocumentOperation(container, OperationType.Query, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(2); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerAndMetrics() { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); } @Test(groups = { "fast", "emulator" }, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void delayedSampling(OperationType operationType) { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientTelemetryConfig clientTelemetryCfg = new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingLogger) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(clientTelemetryCfg); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); String id = UUID.randomUUID().toString(); ObjectNode newItem = getDocumentDefinition(id); container.createItem(newItem); clientTelemetryCfg.sampleDiagnostics(0.25); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeBefore = capturingLogger.getLoggedMessages().size(); clientTelemetryCfg.sampleDiagnostics(0); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore).isEqualTo(loggedMessageSizeAfter); clientTelemetryCfg.sampleDiagnostics(1); executeDocumentOperation(container, operationType, id, newItem); loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore + 1).isEqualTo(loggedMessageSizeAfter); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerWithLegacyOpenTelemetryTraces() { System.setProperty("COSMOS.USE_LEGACY_TRACING", "true"); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); System.setProperty("COSMOS.USE_LEGACY_TRACING", "false"); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void nullPointerDiagnosticsHandler() { NullPointerDiagnosticsHandle capturingHandler = new NullPointerDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); executeTestCase(container); assertThat(systemExited.get()).isFalse(); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandler() throws InterruptedException { System.setProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR", "false"); try { OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); Mono.just(this) .doOnNext(t -> executeTestCase(container)) .subscribeOn(Schedulers.parallel()) .subscribe(); Thread.sleep(2000); assertThat(systemExited.get()).isFalse(); } finally { System.clearProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandlerWithErrorMapper() throws JsonProcessingException { DiagnosticsProviderJvmFatalErrorMapper .getMapper() .registerFatalErrorMapper((error) -> new NullPointerException("test")); OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(ResourceType.Document, OperationType.Create); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); try { executeTestCase(container); fail("should fail with RuntimeException"); } catch (RuntimeException e) { assertThat(e.getCause() instanceof NullPointerException).isTrue(); assertThat(systemExited.get()).isFalse(); } CosmosDiagnostics cosmosDiagnostics = container.upsertItem(getDocumentDefinition(UUID.randomUUID().toString())).getDiagnostics(); ObjectNode cosmosDiagnosticsNode = (ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString()); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount")).isNotNull(); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount").asLong()).isGreaterThan(0); } private CosmosItemResponse<ObjectNode> executeTestCase(CosmosContainer container) { String id = UUID.randomUUID().toString(); CosmosItemResponse<ObjectNode> response = container.createItem( getDocumentDefinition(id), new PartitionKey(id), new CosmosItemRequestOptions()); assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(201); return response; } private ObjectNode getDocumentDefinition(String documentId) { String json = String.format( "{ \"id\": \"%s\", \"mypk\": \"%s\" }", documentId, documentId); try { return OBJECT_MAPPER.readValue(json, ObjectNode.class); } catch (JsonProcessingException jsonError) { fail("No json processing error expected", jsonError); throw new IllegalStateException("No json processing error expected", jsonError); } } private CosmosContainer getContainer(CosmosClientBuilder builder) { CosmosClient oldClient = this.client; if (oldClient != null) { oldClient.close(); } assertThat(builder).isNotNull(); this.client = builder.buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); return this.client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } private CosmosDiagnostics executeDocumentOperation( CosmosContainer cosmosContainer, OperationType operationType, String createdItemId, ObjectNode createdItem) { final AtomicReference<CosmosDiagnostics> diagnostics = new AtomicReference<>(null); switch (operationType) { case Query: String query = String.format("SELECT * from c"); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); queryRequestOptions.setFeedRange(FeedRange.forLogicalPartition(new PartitionKey(createdItemId))); Iterable<FeedResponse<JsonNode>> queryResults = cosmosContainer.queryItems(query, queryRequestOptions, JsonNode.class).iterableByPage(); queryResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case ReadFeed: CosmosChangeFeedRequestOptions changeFeedRequestOptions = CosmosChangeFeedRequestOptions .createForProcessingFromBeginning(FeedRange.forFullRange()); Iterable<FeedResponse<JsonNode>> changeFeedResults = cosmosContainer.queryChangeFeed(changeFeedRequestOptions, JsonNode.class).iterableByPage(); changeFeedResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case Read: CosmosItemResponse<JsonNode> readResponse = cosmosContainer .readItem(createdItemId, new PartitionKey(createdItemId), JsonNode.class); diagnostics.set(readResponse.getDiagnostics()); break; case Replace: CosmosItemResponse<JsonNode> replaceResponse = cosmosContainer .replaceItem(createdItem, createdItemId, new PartitionKey(createdItemId), new CosmosItemRequestOptions()); diagnostics.set(replaceResponse.getDiagnostics()); break; case Delete: try { CosmosItemResponse<Object> deleteResponse = cosmosContainer.deleteItem(getDocumentDefinition(UUID.randomUUID().toString()), new CosmosItemRequestOptions()); diagnostics.set(deleteResponse.getDiagnostics()); } catch (CosmosException e) { if (!Exceptions.isNotFound(e)) { throw e; } } break; case Create: CosmosItemResponse<JsonNode> createResponse = cosmosContainer.createItem(getDocumentDefinition(UUID.randomUUID().toString())); diagnostics.set(createResponse.getDiagnostics()); break; default: throw new IllegalArgumentException("The operation type is not supported"); } return diagnostics.get(); } private static class CapturingDiagnosticsHandler implements CosmosDiagnosticsHandler { private final ArrayList<CosmosDiagnosticsContext> diagnosticsContexts = new ArrayList<>(); @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { diagnosticsContexts.add(diagnosticsContext); } public List<CosmosDiagnosticsContext> getDiagnosticsContexts() { return this.diagnosticsContexts; } } private static class CapturingLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public CapturingLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {} - json: {}", ctx, ctx != null ? ctx.toJson() : "n/a"); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); logger.info(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class ConsoleOutLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public ConsoleOutLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {}", ctx); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); System.out.println(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class NullPointerDiagnosticsHandle implements CosmosDiagnosticsHandler { @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { throw new NullPointerException("NullPointerDiagnosticsHandle"); } } private static class OOMDiagnosticsHandle implements CosmosDiagnosticsHandler { private ResourceType resourceType; private OperationType operationType; private final boolean oomLimitByResourceAndOperationType; public OOMDiagnosticsHandle(ResourceType resourceType, OperationType operationType) { this.resourceType = resourceType; this.operationType = operationType; this.oomLimitByResourceAndOperationType = true; } public OOMDiagnosticsHandle() { this.oomLimitByResourceAndOperationType = false; } @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { if (this.oomLimitByResourceAndOperationType) { if (diagnosticsContext.getOperationType() == this.operationType.toString() && diagnosticsContext.getResourceType() == this.resourceType.toString()) { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } else { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } } }
Discussed offline - validation has been added for sampling rate 1 and 0 - so all code paths are covered by the tests added.
public void onlyCustomLoggerAlwaysSampledOut() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(0); }
.sampleDiagnostics(0)
public void onlyCustomLoggerAlwaysSampledOut() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(0); }
class CosmosDiagnosticsE2ETest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().configure( JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true ); private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosDiagnosticsE2ETest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"fast", "emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.client).isNull(); } @AfterClass(groups = {"fast", "emulator"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { clientSnapshot.close(); } } @DataProvider public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Delete }, { OperationType.Query } }; } public String resolveTestNameSuffix(Object[] row) { return ""; } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomDiagnosticsHandler() { CapturingDiagnosticsHandler capturingHandler = new CapturingDiagnosticsHandler(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingHandler) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); assertThat(capturingHandler.getDiagnosticsContexts()).hasSize(1); CosmosDiagnosticsContext ctx = capturingHandler.getDiagnosticsContexts().get(0); assertThat(ctx).isNotNull(); assertThat(ctx.isCompleted()).isEqualTo(true); assertThat(ctx.getDiagnostics()).isNotEmpty(); assertThat(ctx.getContainerName()).isEqualTo(container.getId()); assertThat(ctx.getDatabaseName()).isEqualTo(container.asyncContainer.getDatabase().getId()); assertThat(ctx.getDuration()).isNotNull(); assertThat(ctx.getDuration()).isGreaterThan(Duration.ZERO); assertThat(ctx.getFinalError()).isNull(); assertThat(ctx.getMaxItemCount()).isNull(); if (this.getClientBuilder().isContentResponseOnWriteEnabled()) { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isGreaterThan(0); } else { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isEqualTo(0); } assertThat(ctx.getOperationType()).isEqualTo(OperationType.Create.toString()); assertThat(ctx.getOperationTypeInternal()).isEqualTo(OperationType.Create); assertThat(ctx.getResourceType()).isEqualTo(ResourceType.Document.toString()); assertThat(ctx.getResourceTypeInternal()).isEqualTo(ResourceType.Document); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyDefaultLogger() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerWithCustomConfig() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerAlwaysSampledOut() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomLoggerWithCustomConfig() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) ); CosmosContainer container = this.getContainer(builder); String id = UUID.randomUUID().toString(); ObjectNode doc = getDocumentDefinition(id); CosmosDiagnostics diagnostics = executeDocumentOperation(container, OperationType.Create, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); diagnostics = executeDocumentOperation(container, OperationType.Query, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(2); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerAndMetrics() { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); } @Test(groups = { "fast", "emulator" }, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void delayedSampling(OperationType operationType) { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientTelemetryConfig clientTelemetryCfg = new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingLogger) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(clientTelemetryCfg); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); String id = UUID.randomUUID().toString(); ObjectNode newItem = getDocumentDefinition(id); container.createItem(newItem); clientTelemetryCfg.sampleDiagnostics(0.25); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeBefore = capturingLogger.getLoggedMessages().size(); clientTelemetryCfg.sampleDiagnostics(0); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore).isEqualTo(loggedMessageSizeAfter); clientTelemetryCfg.sampleDiagnostics(1); executeDocumentOperation(container, operationType, id, newItem); loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore + 1).isEqualTo(loggedMessageSizeAfter); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerWithLegacyOpenTelemetryTraces() { System.setProperty("COSMOS.USE_LEGACY_TRACING", "true"); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); System.setProperty("COSMOS.USE_LEGACY_TRACING", "false"); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void nullPointerDiagnosticsHandler() { NullPointerDiagnosticsHandle capturingHandler = new NullPointerDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); executeTestCase(container); assertThat(systemExited.get()).isFalse(); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandler() throws InterruptedException { System.setProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR", "false"); try { OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); Mono.just(this) .doOnNext(t -> executeTestCase(container)) .subscribeOn(Schedulers.parallel()) .subscribe(); Thread.sleep(2000); assertThat(systemExited.get()).isFalse(); } finally { System.clearProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandlerWithErrorMapper() throws JsonProcessingException { DiagnosticsProviderJvmFatalErrorMapper .getMapper() .registerFatalErrorMapper((error) -> new NullPointerException("test")); OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(ResourceType.Document, OperationType.Create); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); try { executeTestCase(container); fail("should fail with RuntimeException"); } catch (RuntimeException e) { assertThat(e.getCause() instanceof NullPointerException).isTrue(); assertThat(systemExited.get()).isFalse(); } CosmosDiagnostics cosmosDiagnostics = container.upsertItem(getDocumentDefinition(UUID.randomUUID().toString())).getDiagnostics(); ObjectNode cosmosDiagnosticsNode = (ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString()); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount")).isNotNull(); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount").asLong()).isGreaterThan(0); } private CosmosItemResponse<ObjectNode> executeTestCase(CosmosContainer container) { String id = UUID.randomUUID().toString(); CosmosItemResponse<ObjectNode> response = container.createItem( getDocumentDefinition(id), new PartitionKey(id), new CosmosItemRequestOptions()); assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(201); return response; } private ObjectNode getDocumentDefinition(String documentId) { String json = String.format( "{ \"id\": \"%s\", \"mypk\": \"%s\" }", documentId, documentId); try { return OBJECT_MAPPER.readValue(json, ObjectNode.class); } catch (JsonProcessingException jsonError) { fail("No json processing error expected", jsonError); throw new IllegalStateException("No json processing error expected", jsonError); } } private CosmosContainer getContainer(CosmosClientBuilder builder) { CosmosClient oldClient = this.client; if (oldClient != null) { oldClient.close(); } assertThat(builder).isNotNull(); this.client = builder.buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); return this.client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } private CosmosDiagnostics executeDocumentOperation( CosmosContainer cosmosContainer, OperationType operationType, String createdItemId, ObjectNode createdItem) { final AtomicReference<CosmosDiagnostics> diagnostics = new AtomicReference<>(null); switch (operationType) { case Query: String query = String.format("SELECT * from c"); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); queryRequestOptions.setFeedRange(FeedRange.forLogicalPartition(new PartitionKey(createdItemId))); Iterable<FeedResponse<JsonNode>> queryResults = cosmosContainer.queryItems(query, queryRequestOptions, JsonNode.class).iterableByPage(); queryResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case ReadFeed: CosmosChangeFeedRequestOptions changeFeedRequestOptions = CosmosChangeFeedRequestOptions .createForProcessingFromBeginning(FeedRange.forFullRange()); Iterable<FeedResponse<JsonNode>> changeFeedResults = cosmosContainer.queryChangeFeed(changeFeedRequestOptions, JsonNode.class).iterableByPage(); changeFeedResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case Read: CosmosItemResponse<JsonNode> readResponse = cosmosContainer .readItem(createdItemId, new PartitionKey(createdItemId), JsonNode.class); diagnostics.set(readResponse.getDiagnostics()); break; case Replace: CosmosItemResponse<JsonNode> replaceResponse = cosmosContainer .replaceItem(createdItem, createdItemId, new PartitionKey(createdItemId), new CosmosItemRequestOptions()); diagnostics.set(replaceResponse.getDiagnostics()); break; case Delete: try { CosmosItemResponse<Object> deleteResponse = cosmosContainer.deleteItem(getDocumentDefinition(UUID.randomUUID().toString()), new CosmosItemRequestOptions()); diagnostics.set(deleteResponse.getDiagnostics()); } catch (CosmosException e) { if (!Exceptions.isNotFound(e)) { throw e; } } break; case Create: CosmosItemResponse<JsonNode> createResponse = cosmosContainer.createItem(getDocumentDefinition(UUID.randomUUID().toString())); diagnostics.set(createResponse.getDiagnostics()); break; default: throw new IllegalArgumentException("The operation type is not supported"); } return diagnostics.get(); } private static class CapturingDiagnosticsHandler implements CosmosDiagnosticsHandler { private final ArrayList<CosmosDiagnosticsContext> diagnosticsContexts = new ArrayList<>(); @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { diagnosticsContexts.add(diagnosticsContext); } public List<CosmosDiagnosticsContext> getDiagnosticsContexts() { return this.diagnosticsContexts; } } private static class CapturingLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public CapturingLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {} - json: {}", ctx, ctx != null ? ctx.toJson() : "n/a"); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); logger.info(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class ConsoleOutLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public ConsoleOutLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {}", ctx); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); System.out.println(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class NullPointerDiagnosticsHandle implements CosmosDiagnosticsHandler { @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { throw new NullPointerException("NullPointerDiagnosticsHandle"); } } private static class OOMDiagnosticsHandle implements CosmosDiagnosticsHandler { private ResourceType resourceType; private OperationType operationType; private final boolean oomLimitByResourceAndOperationType; public OOMDiagnosticsHandle(ResourceType resourceType, OperationType operationType) { this.resourceType = resourceType; this.operationType = operationType; this.oomLimitByResourceAndOperationType = true; } public OOMDiagnosticsHandle() { this.oomLimitByResourceAndOperationType = false; } @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { if (this.oomLimitByResourceAndOperationType) { if (diagnosticsContext.getOperationType() == this.operationType.toString() && diagnosticsContext.getResourceType() == this.resourceType.toString()) { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } else { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } } }
class CosmosDiagnosticsE2ETest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().configure( JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true ); private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosDiagnosticsE2ETest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"fast", "emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { assertThat(this.client).isNull(); } @AfterClass(groups = {"fast", "emulator"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { clientSnapshot.close(); } } @DataProvider public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Delete }, { OperationType.Query } }; } public String resolveTestNameSuffix(Object[] row) { return ""; } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomDiagnosticsHandler() { CapturingDiagnosticsHandler capturingHandler = new CapturingDiagnosticsHandler(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingHandler) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); assertThat(capturingHandler.getDiagnosticsContexts()).hasSize(1); CosmosDiagnosticsContext ctx = capturingHandler.getDiagnosticsContexts().get(0); assertThat(ctx).isNotNull(); assertThat(ctx.isCompleted()).isEqualTo(true); assertThat(ctx.getDiagnostics()).isNotEmpty(); assertThat(ctx.getContainerName()).isEqualTo(container.getId()); assertThat(ctx.getDatabaseName()).isEqualTo(container.asyncContainer.getDatabase().getId()); assertThat(ctx.getDuration()).isNotNull(); assertThat(ctx.getDuration()).isGreaterThan(Duration.ZERO); assertThat(ctx.getFinalError()).isNull(); assertThat(ctx.getMaxItemCount()).isNull(); if (this.getClientBuilder().isContentResponseOnWriteEnabled()) { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isGreaterThan(0); } else { assertThat(ctx.getMaxResponsePayloadSizeInBytes()).isEqualTo(0); } assertThat(ctx.getOperationType()).isEqualTo(OperationType.Create.toString()); assertThat(ctx.getOperationTypeInternal()).isEqualTo(OperationType.Create); assertThat(ctx.getResourceType()).isEqualTo(ResourceType.Document.toString()); assertThat(ctx.getResourceTypeInternal()).isEqualTo(ResourceType.Document); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyDefaultLogger() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerWithCustomConfig() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyLoggerAlwaysSampledOut() { CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .sampleDiagnostics(0) ); CosmosContainer container = this.getContainer(builder); CosmosItemResponse<ObjectNode> response = executeTestCase(container); assertThat(response.getDiagnostics()).isNotNull(); assertThat(response.getDiagnostics().getDiagnosticsContext()).isNotNull(); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void onlyCustomLoggerWithCustomConfig() { CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsThresholds( new CosmosDiagnosticsThresholds() .setPointOperationLatencyThreshold(Duration.ofMillis(100)) .setNonPointOperationLatencyThreshold(Duration.ofMillis(2000)) .setRequestChargeThreshold(100) ) .diagnosticsHandler(capturingLogger) ); CosmosContainer container = this.getContainer(builder); String id = UUID.randomUUID().toString(); ObjectNode doc = getDocumentDefinition(id); CosmosDiagnostics diagnostics = executeDocumentOperation(container, OperationType.Create, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); diagnostics = executeDocumentOperation(container, OperationType.Query, id, doc); assertThat(diagnostics).isNotNull(); assertThat(diagnostics.getDiagnosticsContext()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).isNotNull(); assertThat(capturingLogger.getLoggedMessages()).hasSize(2); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerAndMetrics() { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); } @Test(groups = { "fast", "emulator" }, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void delayedSampling(OperationType operationType) { MeterRegistry meterRegistry = ConsoleLoggingRegistryFactory.create(1); CapturingLogger capturingLogger = new CapturingLogger(); CosmosClientTelemetryConfig clientTelemetryCfg = new CosmosClientTelemetryConfig() .diagnosticsHandler(capturingLogger) .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(meterRegistry)); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(clientTelemetryCfg); CosmosContainer container = this.getContainer(builder); executeTestCase(container); meterRegistry.clear(); meterRegistry.close(); String id = UUID.randomUUID().toString(); ObjectNode newItem = getDocumentDefinition(id); container.createItem(newItem); clientTelemetryCfg.sampleDiagnostics(0.25); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeBefore = capturingLogger.getLoggedMessages().size(); clientTelemetryCfg.sampleDiagnostics(0); executeDocumentOperation(container, operationType, id, newItem); int loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore).isEqualTo(loggedMessageSizeAfter); clientTelemetryCfg.sampleDiagnostics(1); executeDocumentOperation(container, operationType, id, newItem); loggedMessageSizeAfter = capturingLogger.getLoggedMessages().size(); assertThat(loggedMessageSizeBefore + 1).isEqualTo(loggedMessageSizeAfter); } @Test(groups = { "fast", "emulator" }, timeOut = TIMEOUT) public void defaultLoggerWithLegacyOpenTelemetryTraces() { System.setProperty("COSMOS.USE_LEGACY_TRACING", "true"); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig( new CosmosClientTelemetryConfig() .diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER) ); CosmosContainer container = this.getContainer(builder); executeTestCase(container); System.setProperty("COSMOS.USE_LEGACY_TRACING", "false"); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void nullPointerDiagnosticsHandler() { NullPointerDiagnosticsHandle capturingHandler = new NullPointerDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); executeTestCase(container); assertThat(systemExited.get()).isFalse(); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandler() throws InterruptedException { System.setProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR", "false"); try { OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); Mono.just(this) .doOnNext(t -> executeTestCase(container)) .subscribeOn(Schedulers.parallel()) .subscribe(); Thread.sleep(2000); assertThat(systemExited.get()).isFalse(); } finally { System.clearProperty("COSMOS.DIAGNOSTICS_PROVIDER_SYSTEM_EXIT_ON_ERROR"); } } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void OOMDiagnosticsHandlerWithErrorMapper() throws JsonProcessingException { DiagnosticsProviderJvmFatalErrorMapper .getMapper() .registerFatalErrorMapper((error) -> new NullPointerException("test")); OOMDiagnosticsHandle capturingHandler = new OOMDiagnosticsHandle(ResourceType.Document, OperationType.Create); CosmosClientBuilder builder = this .getClientBuilder() .clientTelemetryConfig(new CosmosClientTelemetryConfig().diagnosticsHandler(capturingHandler)); CosmosContainer container = this.getContainer(builder); AtomicBoolean systemExited = new AtomicBoolean(false); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { systemExited.set(true); } }); try { executeTestCase(container); fail("should fail with RuntimeException"); } catch (RuntimeException e) { assertThat(e.getCause() instanceof NullPointerException).isTrue(); assertThat(systemExited.get()).isFalse(); } CosmosDiagnostics cosmosDiagnostics = container.upsertItem(getDocumentDefinition(UUID.randomUUID().toString())).getDiagnostics(); ObjectNode cosmosDiagnosticsNode = (ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString()); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount")).isNotNull(); assertThat(cosmosDiagnosticsNode.get("jvmFatalErrorMapperExecutionCount").asLong()).isGreaterThan(0); } private CosmosItemResponse<ObjectNode> executeTestCase(CosmosContainer container) { String id = UUID.randomUUID().toString(); CosmosItemResponse<ObjectNode> response = container.createItem( getDocumentDefinition(id), new PartitionKey(id), new CosmosItemRequestOptions()); assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(201); return response; } private ObjectNode getDocumentDefinition(String documentId) { String json = String.format( "{ \"id\": \"%s\", \"mypk\": \"%s\" }", documentId, documentId); try { return OBJECT_MAPPER.readValue(json, ObjectNode.class); } catch (JsonProcessingException jsonError) { fail("No json processing error expected", jsonError); throw new IllegalStateException("No json processing error expected", jsonError); } } private CosmosContainer getContainer(CosmosClientBuilder builder) { CosmosClient oldClient = this.client; if (oldClient != null) { oldClient.close(); } assertThat(builder).isNotNull(); this.client = builder.buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); return this.client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } private CosmosDiagnostics executeDocumentOperation( CosmosContainer cosmosContainer, OperationType operationType, String createdItemId, ObjectNode createdItem) { final AtomicReference<CosmosDiagnostics> diagnostics = new AtomicReference<>(null); switch (operationType) { case Query: String query = String.format("SELECT * from c"); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); queryRequestOptions.setFeedRange(FeedRange.forLogicalPartition(new PartitionKey(createdItemId))); Iterable<FeedResponse<JsonNode>> queryResults = cosmosContainer.queryItems(query, queryRequestOptions, JsonNode.class).iterableByPage(); queryResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case ReadFeed: CosmosChangeFeedRequestOptions changeFeedRequestOptions = CosmosChangeFeedRequestOptions .createForProcessingFromBeginning(FeedRange.forFullRange()); Iterable<FeedResponse<JsonNode>> changeFeedResults = cosmosContainer.queryChangeFeed(changeFeedRequestOptions, JsonNode.class).iterableByPage(); changeFeedResults.forEach(t -> diagnostics.set(t.getCosmosDiagnostics())); break; case Read: CosmosItemResponse<JsonNode> readResponse = cosmosContainer .readItem(createdItemId, new PartitionKey(createdItemId), JsonNode.class); diagnostics.set(readResponse.getDiagnostics()); break; case Replace: CosmosItemResponse<JsonNode> replaceResponse = cosmosContainer .replaceItem(createdItem, createdItemId, new PartitionKey(createdItemId), new CosmosItemRequestOptions()); diagnostics.set(replaceResponse.getDiagnostics()); break; case Delete: try { CosmosItemResponse<Object> deleteResponse = cosmosContainer.deleteItem(getDocumentDefinition(UUID.randomUUID().toString()), new CosmosItemRequestOptions()); diagnostics.set(deleteResponse.getDiagnostics()); } catch (CosmosException e) { if (!Exceptions.isNotFound(e)) { throw e; } } break; case Create: CosmosItemResponse<JsonNode> createResponse = cosmosContainer.createItem(getDocumentDefinition(UUID.randomUUID().toString())); diagnostics.set(createResponse.getDiagnostics()); break; default: throw new IllegalArgumentException("The operation type is not supported"); } return diagnostics.get(); } private static class CapturingDiagnosticsHandler implements CosmosDiagnosticsHandler { private final ArrayList<CosmosDiagnosticsContext> diagnosticsContexts = new ArrayList<>(); @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { diagnosticsContexts.add(diagnosticsContext); } public List<CosmosDiagnosticsContext> getDiagnosticsContexts() { return this.diagnosticsContexts; } } private static class CapturingLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public CapturingLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {} - json: {}", ctx, ctx != null ? ctx.toJson() : "n/a"); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); logger.info(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class ConsoleOutLogger implements CosmosDiagnosticsHandler { private final List<String> loggedMessages = new ArrayList<>(); public ConsoleOutLogger() { super(); } @Override public void handleDiagnostics(CosmosDiagnosticsContext ctx, Context traceContext) { logger.info("--> log - ctx: {}", ctx); String msg = String.format( "Account: %s -> DB: %s, Col:%s, StatusCode: %d:%d Diagnostics: %s", ctx.getAccountName(), ctx.getDatabaseName(), ctx.getContainerName(), ctx.getStatusCode(), ctx.getSubStatusCode(), ctx); this.loggedMessages.add(msg); System.out.println(msg); } public List<String> getLoggedMessages() { return this.loggedMessages; } } private static class NullPointerDiagnosticsHandle implements CosmosDiagnosticsHandler { @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { throw new NullPointerException("NullPointerDiagnosticsHandle"); } } private static class OOMDiagnosticsHandle implements CosmosDiagnosticsHandler { private ResourceType resourceType; private OperationType operationType; private final boolean oomLimitByResourceAndOperationType; public OOMDiagnosticsHandle(ResourceType resourceType, OperationType operationType) { this.resourceType = resourceType; this.operationType = operationType; this.oomLimitByResourceAndOperationType = true; } public OOMDiagnosticsHandle() { this.oomLimitByResourceAndOperationType = false; } @Override public void handleDiagnostics(CosmosDiagnosticsContext diagnosticsContext, Context traceContext) { if (this.oomLimitByResourceAndOperationType) { if (diagnosticsContext.getOperationType() == this.operationType.toString() && diagnosticsContext.getResourceType() == this.resourceType.toString()) { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } else { throw new OutOfMemoryError("OOMDiagnosticsHandle"); } } } }
nit, core actually has https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersPolicy.java
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null && this.azureResourceId != null) { policies.add(new TranslatorRegionAuthenticationPolicy(this.region)); policies.add(new TranslatorResourceIdAuthenticationPolicy(this.azureResourceId)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { policies.add(new TranslatorRegionAuthenticationPolicy(this.region)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
policies.add(new TranslatorResourceIdAuthenticationPolicy(this.azureResourceId));
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null || this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private String region; private String azureResourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code redion} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param azureResourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code azureResourceId} is null. */ public TextTranslationClientBuilder azureResourceId(String azureResourceId) { Objects.requireNonNull(azureResourceId, "'azureResourceId' cannot be null."); this.azureResourceId = azureResourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } if (tokenCredential != null && (this.region != null || this.resourceId != null)) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); } if (this.credential != null && !CoreUtils.isNullOrEmpty(this.resourceId)) { throw LOGGER.logExceptionAsError( new IllegalStateException("Resource Id cannot be used with key credential. Set resourceId to null.")); } if (tokenCredential != null && this.credential != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Both token credential and key credential cannot be set.")); } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
Good, I switched to that.
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null && this.azureResourceId != null) { policies.add(new TranslatorRegionAuthenticationPolicy(this.region)); policies.add(new TranslatorResourceIdAuthenticationPolicy(this.azureResourceId)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { policies.add(new TranslatorRegionAuthenticationPolicy(this.region)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
policies.add(new TranslatorResourceIdAuthenticationPolicy(this.azureResourceId));
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null || this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private String region; private String azureResourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code redion} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param azureResourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code azureResourceId} is null. */ public TextTranslationClientBuilder azureResourceId(String azureResourceId) { Objects.requireNonNull(azureResourceId, "'azureResourceId' cannot be null."); this.azureResourceId = azureResourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } if (tokenCredential != null && (this.region != null || this.resourceId != null)) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); } if (this.credential != null && !CoreUtils.isNullOrEmpty(this.resourceId)) { throw LOGGER.logExceptionAsError( new IllegalStateException("Resource Id cannot be used with key credential. Set resourceId to null.")); } if (tokenCredential != null && this.credential != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Both token credential and key credential cannot be set.")); } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
Will AAD auth work if these headers are not set?
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null && this.azureResourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.azureResourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
}
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null || this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String azureResourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param azureResourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code azureResourceId} is null. */ public TextTranslationClientBuilder azureResourceId(String azureResourceId) { Objects.requireNonNull(azureResourceId, "'azureResourceId' cannot be null."); this.azureResourceId = azureResourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } if (tokenCredential != null && (this.region != null || this.resourceId != null)) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); } if (this.credential != null && !CoreUtils.isNullOrEmpty(this.resourceId)) { throw LOGGER.logExceptionAsError( new IllegalStateException("Resource Id cannot be used with key credential. Set resourceId to null.")); } if (tokenCredential != null && this.credential != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Both token credential and key credential cannot be set.")); } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
Without those headers the AAD authentication will be failing for general MT endpoint. It will still work for custom endpoint.
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null && this.azureResourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.azureResourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
}
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null || this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String azureResourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param azureResourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code azureResourceId} is null. */ public TextTranslationClientBuilder azureResourceId(String azureResourceId) { Objects.requireNonNull(azureResourceId, "'azureResourceId' cannot be null."); this.azureResourceId = azureResourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } if (tokenCredential != null && (this.region != null || this.resourceId != null)) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); } if (this.credential != null && !CoreUtils.isNullOrEmpty(this.resourceId)) { throw LOGGER.logExceptionAsError( new IllegalStateException("Resource Id cannot be used with key credential. Set resourceId to null.")); } if (tokenCredential != null && this.credential != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Both token credential and key credential cannot be set.")); } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
What if one of them is null and the other is not? We should throw an error in this case as ignoring one of them silently will give the impression that region/resourceId is being used.
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null && this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
if (this.region != null && this.resourceId != null) {
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null || this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } if (tokenCredential != null && (this.region != null || this.resourceId != null)) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); } if (this.credential != null && !CoreUtils.isNullOrEmpty(this.resourceId)) { throw LOGGER.logExceptionAsError( new IllegalStateException("Resource Id cannot be used with key credential. Set resourceId to null.")); } if (tokenCredential != null && this.credential != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Both token credential and key credential cannot be set.")); } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
Added check.
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null && this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
if (this.region != null && this.resourceId != null) {
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null || this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } if (tokenCredential != null && (this.region != null || this.resourceId != null)) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); } if (this.credential != null && !CoreUtils.isNullOrEmpty(this.resourceId)) { throw LOGGER.logExceptionAsError( new IllegalStateException("Resource Id cannot be used with key credential. Set resourceId to null.")); } if (tokenCredential != null && this.credential != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Both token credential and key credential cannot be set.")); } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
nit: this can be removed as this is already done above. ```suggestion ```
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null || this.resourceId != null) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null.");
private HttpPipeline createHttpPipeline() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); HttpHeaders headers = new HttpHeaders(); localClientOptions.getHeaders() .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); if (headers.getSize() > 0) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) .forEach(p -> policies.add(p)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); if (this.region != null || this.resourceId != null) { HttpHeaders aadHeaders = new HttpHeaders(); aadHeaders.put(OCP_APIM_RESOURCE_ID_KEY, this.resourceId); aadHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(aadHeaders)); } } if (this.credential != null) { policies.add(new KeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); if (this.region != null) { HttpHeaders regionHeaders = new HttpHeaders(); regionHeaders.put(OCP_APIM_SUBSCRIPTION_REGION, this.region); policies.add(new AddHeadersPolicy(regionHeaders)); } } this.pipelinePolicies.stream().filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .forEach(p -> policies.add(p)); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(localHttpLogOptions)); HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient).clientOptions(localClientOptions).build(); return httpPipeline; }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } if (tokenCredential != null && (this.region != null || this.resourceId != null)) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); } if (this.credential != null && !CoreUtils.isNullOrEmpty(this.resourceId)) { throw LOGGER.logExceptionAsError( new IllegalStateException("Resource Id cannot be used with key credential. Set resourceId to null.")); } if (tokenCredential != null && this.credential != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Both token credential and key credential cannot be set.")); } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
class TextTranslationClientBuilder implements HttpTrait<TextTranslationClientBuilder>, ConfigurationTrait<TextTranslationClientBuilder>, EndpointTrait<TextTranslationClientBuilder>, KeyCredentialTrait<TextTranslationClientBuilder>, TokenCredentialTrait<TextTranslationClientBuilder> { @Generated private static final String SDK_NAME = "name"; @Generated private static final String SDK_VERSION = "version"; private static final String DEFAULT_SCOPE = "https: private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; private static final String OCP_APIM_SUBSCRIPTION_REGION = "Ocp-Apim-Subscription-Region"; private static final String OCP_APIM_RESOURCE_ID_KEY = "Ocp-Apim-ResourceId"; private String region; private String resourceId; private KeyCredential credential; private TokenCredential tokenCredential; @Generated private static final Map<String, String> PROPERTIES = CoreUtils.getProperties("azure-ai-translation-text.properties"); @Generated private final List<HttpPipelinePolicy> pipelinePolicies; /** * Create an instance of the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder() { this.pipelinePolicies = new ArrayList<>(); } /* * The HTTP pipeline to send requests through. */ @Generated private HttpPipeline pipeline; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /* * The HTTP client used to send the request. */ @Generated private HttpClient httpClient; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /* * The logging configuration for HTTP requests and responses. */ @Generated private HttpLogOptions httpLogOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /* * The client options such as application ID and custom headers to set on a request. */ @Generated private ClientOptions clientOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /* * The retry options to configure retry policy for failed requests. */ @Generated private RetryOptions retryOptions; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); pipelinePolicies.add(customPolicy); return this; } /* * The configuration store that is used during construction of the service client. */ @Generated private Configuration configuration; /** * {@inheritDoc}. */ @Generated @Override public TextTranslationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /* * The service endpoint */ @Generated private String endpoint; private Boolean isCustomEndpoint = false; /** * {@inheritDoc}. */ @Override public TextTranslationClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; this.isCustomEndpoint = CustomEndpointUtils.isPlatformHost(endpoint); return this; } /* * Service version */ @Generated private TextTranslationServiceVersion serviceVersion; /** * Sets Service version. * * @param serviceVersion the serviceVersion value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder serviceVersion(TextTranslationServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /* * The retry policy that will attempt to retry failed requests, if applicable. */ @Generated private RetryPolicy retryPolicy; /** * Sets The retry policy that will attempt to retry failed requests, if applicable. * * @param retryPolicy the retryPolicy value. * @return the TextTranslationClientBuilder. */ @Generated public TextTranslationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link KeyCredential} used to authorize requests sent to the service. * * @param credential {@link KeyCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code credential} is null. */ public TextTranslationClientBuilder credential(KeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; } /** * Sets the region used to authorize requests sent to the service. * * @param region where the Translator resource is created. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code region} is null. */ public TextTranslationClientBuilder region(String region) { Objects.requireNonNull(region, "'region' cannot be null."); this.region = region; return this; } /** * Sets the Azure Resource Id used to authorize requests sent to the service. * * @param resourceId Id of the Translator Resource. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code resourceId} is null. */ public TextTranslationClientBuilder resourceId(String resourceId) { Objects.requireNonNull(resourceId, "'resourceId' cannot be null."); this.resourceId = resourceId; return this; } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. * @return The updated {@link TextTranslationClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public TextTranslationClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; } /** * Builds an instance of TextTranslationClientImpl with the provided parameters. * * @return an instance of TextTranslationClientImpl. */ private TextTranslationClientImpl buildInnerClient() { HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); TextTranslationServiceVersion localServiceVersion = (serviceVersion != null) ? serviceVersion : TextTranslationServiceVersion.getLatest(); String serviceEndpoint; if (this.endpoint == null) { serviceEndpoint = "https: } else if (this.isCustomEndpoint) { try { URL hostUri = new URL(endpoint); URL fullUri = new URL(hostUri, "/translator/text/v" + localServiceVersion.getVersion()); serviceEndpoint = fullUri.toString(); } catch (MalformedURLException ex) { serviceEndpoint = endpoint; } } else { serviceEndpoint = endpoint; } if (tokenCredential != null && (this.region != null || this.resourceId != null)) { Objects.requireNonNull(this.region, "'region' cannot be null."); Objects.requireNonNull(this.resourceId, "'resourceId' cannot be null."); } if (this.credential != null && !CoreUtils.isNullOrEmpty(this.resourceId)) { throw LOGGER.logExceptionAsError( new IllegalStateException("Resource Id cannot be used with key credential. Set resourceId to null.")); } if (tokenCredential != null && this.credential != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Both token credential and key credential cannot be set.")); } TextTranslationClientImpl client = new TextTranslationClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), serviceEndpoint, localServiceVersion); return client; } /** * Builds an instance of TextTranslationAsyncClient class. * * @return an instance of TextTranslationAsyncClient. */ @Generated public TextTranslationAsyncClient buildAsyncClient() { return new TextTranslationAsyncClient(buildInnerClient()); } /** * Builds an instance of TextTranslationClient class. * * @return an instance of TextTranslationClient. */ @Generated public TextTranslationClient buildClient() { return new TextTranslationClient(buildInnerClient()); } private static final ClientLogger LOGGER = new ClientLogger(TextTranslationClientBuilder.class); }
Why we need to call `ensureIpSecurityRestrictions()`? Anything here related to IP?
public FluentImplT enablePublicNetworkAccess() { this.ensureIpSecurityRestrictions(); this.siteConfig.withPublicNetworkAccess("Enabled"); return (FluentImplT) this; }
this.ensureIpSecurityRestrictions();
public FluentImplT enablePublicNetworkAccess() { if (Objects.isNull(this.siteConfig)) { this.siteConfig = new SiteConfigResourceInner(); } this.siteConfig.withPublicNetworkAccess("Enabled"); return (FluentImplT) this; }
class PipedInputStreamWithCallback extends PipedInputStream { private Runnable callback; private void addCallback(Runnable action) { this.callback = action; } @Override public void close() throws IOException { callback.run(); super.close(); } }
class PipedInputStreamWithCallback extends PipedInputStream { private Runnable callback; private void addCallback(Runnable action) { this.callback = action; } @Override public void close() throws IOException { callback.run(); super.close(); } }
What's difference from just `return this.innerModel().publicNetworkAccess()`? Same on other instances.
public PublicNetworkAccess publicNetworkAccess() { return Objects.isNull(this.innerModel().publicNetworkAccess()) ? null : this.innerModel().publicNetworkAccess(); }
return Objects.isNull(this.innerModel().publicNetworkAccess()) ? null : this.innerModel().publicNetworkAccess();
public PublicNetworkAccess publicNetworkAccess() { return this.innerModel().publicNetworkAccess(); }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } @Override public KubernetesClusterImpl enablePublicNetworkAccess() { this.innerModel().withPublicNetworkAccess(PublicNetworkAccess.ENABLED); return this; } @Override public KubernetesClusterImpl disablePublicNetworkAccess() { this.innerModel().withPublicNetworkAccess(PublicNetworkAccess.DISABLED); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class KubernetesClusterImpl extends GroupableResourceImpl< KubernetesCluster, ManagedClusterInner, KubernetesClusterImpl, ContainerServiceManager> implements KubernetesCluster, KubernetesCluster.Definition, KubernetesCluster.Update { private final ClientLogger logger = new ClientLogger(getClass()); private List<CredentialResult> adminKubeConfigs; private List<CredentialResult> userKubeConfigs; private final Map<Format, List<CredentialResult>> formatUserKubeConfigsMap = new ConcurrentHashMap<>(); private ManagedClusterInner parameterSnapshotOnUpdate; private static final SerializerAdapter SERIALIZER_ADAPTER = SerializerFactory.createDefaultManagementSerializerAdapter(); protected KubernetesClusterImpl(String name, ManagedClusterInner innerObject, ContainerServiceManager manager) { super(name, innerObject, manager); if (this.innerModel().agentPoolProfiles() == null) { this.innerModel().withAgentPoolProfiles(new ArrayList<>()); } this.adminKubeConfigs = null; this.userKubeConfigs = null; } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public String dnsPrefix() { return this.innerModel().dnsPrefix(); } @Override public String fqdn() { return this.innerModel().fqdn(); } @Override public String version() { return this.innerModel().kubernetesVersion(); } @Override public List<CredentialResult> adminKubeConfigs() { if (this.adminKubeConfigs == null || this.adminKubeConfigs.size() == 0) { this.adminKubeConfigs = this.manager().kubernetesClusters().listAdminKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.adminKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs() { if (this.userKubeConfigs == null || this.userKubeConfigs.size() == 0) { this.userKubeConfigs = this.manager().kubernetesClusters().listUserKubeConfigContent(this.resourceGroupName(), this.name()); } return Collections.unmodifiableList(this.userKubeConfigs); } @Override public List<CredentialResult> userKubeConfigs(Format format) { if (format == null) { return userKubeConfigs(); } return Collections.unmodifiableList( this.formatUserKubeConfigsMap.computeIfAbsent( format, key -> KubernetesClusterImpl.this .manager() .kubernetesClusters() .listUserKubeConfigContent( KubernetesClusterImpl.this.resourceGroupName(), KubernetesClusterImpl.this.name(), format )) ); } @Override public byte[] adminKubeConfigContent() { for (CredentialResult config : adminKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent() { for (CredentialResult config : userKubeConfigs()) { return config.value(); } return new byte[0]; } @Override public byte[] userKubeConfigContent(Format format) { if (format == null) { return userKubeConfigContent(); } for (CredentialResult config : userKubeConfigs(format)) { return config.value(); } return new byte[0]; } @Override public String servicePrincipalClientId() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().clientId(); } else { return null; } } @Override public String servicePrincipalSecret() { if (this.innerModel().servicePrincipalProfile() != null) { return this.innerModel().servicePrincipalProfile().secret(); } else { return null; } } @Override public String linuxRootUsername() { if (this.innerModel().linuxProfile() != null) { return this.innerModel().linuxProfile().adminUsername(); } else { return null; } } @Override public String sshKey() { if (this.innerModel().linuxProfile() == null || this.innerModel().linuxProfile().ssh() == null || this.innerModel().linuxProfile().ssh().publicKeys() == null || this.innerModel().linuxProfile().ssh().publicKeys().size() == 0) { return null; } else { return this.innerModel().linuxProfile().ssh().publicKeys().get(0).keyData(); } } @Override public Map<String, KubernetesClusterAgentPool> agentPools() { Map<String, KubernetesClusterAgentPool> agentPoolMap = new HashMap<>(); if (this.innerModel().agentPoolProfiles() != null && this.innerModel().agentPoolProfiles().size() > 0) { for (ManagedClusterAgentPoolProfile agentPoolProfile : this.innerModel().agentPoolProfiles()) { agentPoolMap.put(agentPoolProfile.name(), new KubernetesClusterAgentPoolImpl(agentPoolProfile, this)); } } return Collections.unmodifiableMap(agentPoolMap); } @Override public ContainerServiceNetworkProfile networkProfile() { return this.innerModel().networkProfile(); } @Override public Map<String, ManagedClusterAddonProfile> addonProfiles() { return this.innerModel().addonProfiles() == null ? Collections.emptyMap() : Collections.unmodifiableMap(this.innerModel().addonProfiles()); } @Override public String nodeResourceGroup() { return this.innerModel().nodeResourceGroup(); } @Override public boolean enableRBAC() { return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableRbac()); } @Override public PowerState powerState() { return this.innerModel().powerState(); } @Override public ManagedClusterSku sku() { return this.innerModel().sku(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { String objectId = null; if (this.innerModel().identityProfile() != null) { UserAssignedIdentity identity = this.innerModel().identityProfile().get("kubeletidentity"); if (identity != null) { objectId = identity.objectId(); } } return objectId; } @Override public List<String> azureActiveDirectoryGroupIds() { if (innerModel().aadProfile() == null || CoreUtils.isNullOrEmpty(innerModel().aadProfile().adminGroupObjectIDs())) { return Collections.emptyList(); } else { return Collections.unmodifiableList(innerModel().aadProfile().adminGroupObjectIDs()); } } @Override public boolean isLocalAccountsEnabled() { return !ResourceManagerUtils.toPrimitiveBoolean(innerModel().disableLocalAccounts()); } @Override public boolean isAzureRbacEnabled() { return innerModel().aadProfile() != null && ResourceManagerUtils.toPrimitiveBoolean(innerModel().aadProfile().enableAzureRbac()); } @Override public String diskEncryptionSetId() { return innerModel().diskEncryptionSetId(); } @Override public String agentPoolResourceGroup() { return innerModel().nodeResourceGroup(); } @Override @Override public void start() { this.startAsync().block(); } @Override public Mono<Void> startAsync() { return manager().kubernetesClusters().startAsync(this.resourceGroupName(), this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager().kubernetesClusters().stopAsync(this.resourceGroupName(), this.name()); } @Override public Accepted<AgentPool> beginCreateAgentPool(String agentPoolName, AgentPoolData agentPool) { return AcceptedImpl.newAccepted( logger, this.manager().serviceClient().getHttpPipeline(), this.manager().serviceClient().getDefaultPollInterval(), () -> this.manager().serviceClient().getAgentPools() .createOrUpdateWithResponseAsync(resourceGroupName(), name(), agentPoolName, agentPool.innerModel()) .block(), AgentPoolDataImpl::new, AgentPoolInner.class, null, Context.NONE); } @Override protected Mono<ManagedClusterInner> getInnerAsync() { return this .manager() .serviceClient() .getManagedClusters() .getByResourceGroupAsync(this.resourceGroupName(), this.name()) .map(inner -> { clearKubeConfig(); return inner; }); } @Override public KubernetesClusterImpl update() { parameterSnapshotOnUpdate = this.deepCopyInner(); parameterSnapshotOnUpdate.withServicePrincipalProfile(null); return super.update(); } boolean isClusterModifiedDuringUpdate(ManagedClusterInner parameter) { if (parameterSnapshotOnUpdate == null || parameter == null) { return true; } else { final List<ManagedClusterAgentPoolProfile> parameterSnapshotAgentPools = parameterSnapshotOnUpdate.agentPoolProfiles(); final List<ManagedClusterAgentPoolProfile> parameterAgentPools = parameter.agentPoolProfiles(); Set<String> intersectAgentPoolNames = parameter.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet()); intersectAgentPoolNames.retainAll(parameterSnapshotOnUpdate.agentPoolProfiles().stream() .map(ManagedClusterAgentPoolProfile::name) .collect(Collectors.toSet())); List<ManagedClusterAgentPoolProfile> agentPools = parameterSnapshotOnUpdate.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameterSnapshotOnUpdate.withAgentPoolProfiles(agentPools); agentPools = parameter.agentPoolProfiles() .stream() .filter(p -> intersectAgentPoolNames.contains(p.name())) .collect(Collectors.toList()); parameter.withAgentPoolProfiles(agentPools); try { String jsonStrSnapshot = SERIALIZER_ADAPTER.serialize(parameterSnapshotOnUpdate, SerializerEncoding.JSON); String jsonStr = SERIALIZER_ADAPTER.serialize(parameter, SerializerEncoding.JSON); return !jsonStr.equals(jsonStrSnapshot); } catch (IOException e) { return true; } finally { parameterSnapshotOnUpdate.withAgentPoolProfiles(parameterSnapshotAgentPools); parameter.withAgentPoolProfiles(parameterAgentPools); } } } ManagedClusterInner deepCopyInner() { ManagedClusterInner updateParameter; try { String jsonStr = SERIALIZER_ADAPTER.serialize(this.innerModel(), SerializerEncoding.JSON); updateParameter = SERIALIZER_ADAPTER.deserialize(jsonStr, ManagedClusterInner.class, SerializerEncoding.JSON); } catch (IOException e) { updateParameter = null; } return updateParameter; } @Override public Mono<KubernetesCluster> createResourceAsync() { final KubernetesClusterImpl self = this; if (!this.isInCreateMode()) { this.innerModel().withServicePrincipalProfile(null); } final boolean createOrModified = this.isInCreateMode() || this.isClusterModifiedDuringUpdate(this.innerModel()); if (createOrModified) { return this .manager() .serviceClient() .getManagedClusters() .createOrUpdateAsync(self.resourceGroupName(), self.name(), self.innerModel()) .map(inner -> { self.setInner(inner); clearKubeConfig(); return self; }); } else { return Mono.just(this); } } private void clearKubeConfig() { this.adminKubeConfigs = null; this.userKubeConfigs = null; this.formatUserKubeConfigsMap.clear(); } @Override public KubernetesClusterImpl withFreeSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.FREE).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withStandardSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.STANDARD).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.KUBERNETES_OFFICIAL); return this; } @Override public KubernetesClusterImpl withPremiumSku() { this.innerModel().withSku(new ManagedClusterSku().withTier(ManagedClusterSkuTier.PREMIUM).withName(ManagedClusterSkuName.BASE)); this.innerModel().withSupportPlan(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT); return this; } @Override public KubernetesClusterImpl withVersion(String kubernetesVersion) { this.innerModel().withKubernetesVersion(kubernetesVersion); return this; } @Override public KubernetesClusterImpl withDefaultVersion() { this.innerModel().withKubernetesVersion(""); return this; } @Override public KubernetesClusterImpl withRootUsername(String rootUserName) { if (this.innerModel().linuxProfile() == null) { this.innerModel().withLinuxProfile(new ContainerServiceLinuxProfile()); } this.innerModel().linuxProfile().withAdminUsername(rootUserName); return this; } @Override public KubernetesClusterImpl withSshKey(String sshKeyData) { this .innerModel() .linuxProfile() .withSsh( new ContainerServiceSshConfiguration().withPublicKeys(new ArrayList<ContainerServiceSshPublicKey>())); this.innerModel().linuxProfile().ssh().publicKeys().add( new ContainerServiceSshPublicKey().withKeyData(sshKeyData)); return this; } @Override public KubernetesClusterImpl withServicePrincipalClientId(String clientId) { this.innerModel().withServicePrincipalProfile( new ManagedClusterServicePrincipalProfile().withClientId(clientId)); return this; } @Override public KubernetesClusterImpl withSystemAssignedManagedServiceIdentity() { this.innerModel().withIdentity(new ManagedClusterIdentity().withType(ResourceIdentityType.SYSTEM_ASSIGNED)); return this; } @Override public KubernetesClusterImpl withServicePrincipalSecret(String secret) { this.innerModel().servicePrincipalProfile().withSecret(secret); return this; } @Override public KubernetesClusterImpl withDnsPrefix(String dnsPrefix) { this.innerModel().withDnsPrefix(dnsPrefix); return this; } @Override public KubernetesClusterAgentPoolImpl defineAgentPool(String name) { ManagedClusterAgentPoolProfile innerPoolProfile = new ManagedClusterAgentPoolProfile() .withName(name) .withOrchestratorVersion(this.innerModel().kubernetesVersion()); return new KubernetesClusterAgentPoolImpl(innerPoolProfile, this); } @Override public KubernetesClusterAgentPoolImpl updateAgentPool(String name) { for (ManagedClusterAgentPoolProfile agentPoolProfile : innerModel().agentPoolProfiles()) { if (agentPoolProfile.name().equals(name)) { return new KubernetesClusterAgentPoolImpl(agentPoolProfile, this); } } throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "Cannot get agent pool named %s", name))); } @Override public Update withoutAgentPool(String name) { if (innerModel().agentPoolProfiles() != null) { innerModel().withAgentPoolProfiles( innerModel().agentPoolProfiles().stream() .filter(p -> !name.equals(p.name())) .collect(Collectors.toList())); this.addDependency(context -> manager().serviceClient().getAgentPools().deleteAsync(resourceGroupName(), name(), name) .then(context.voidMono())); } return this; } @Override public KubernetesCluster.DefinitionStages.NetworkProfileDefinitionStages.Blank< KubernetesCluster.DefinitionStages.WithCreate> defineNetworkProfile() { return new KubernetesClusterNetworkProfileImpl(this); } @Override public KubernetesClusterImpl withAddOnProfiles(Map<String, ManagedClusterAddonProfile> addOnProfileMap) { this.innerModel().withAddonProfiles(addOnProfileMap); return this; } @Override public KubernetesClusterImpl withNetworkProfile(ContainerServiceNetworkProfile networkProfile) { this.innerModel().withNetworkProfile(networkProfile); return this; } @Override public KubernetesClusterImpl withRBACEnabled() { this.innerModel().withEnableRbac(true); return this; } @Override public KubernetesClusterImpl withRBACDisabled() { this.innerModel().withEnableRbac(false); return this; } public KubernetesClusterImpl addNewAgentPool(KubernetesClusterAgentPoolImpl agentPool) { if (!isInCreateMode()) { this.addDependency(context -> manager().serviceClient().getAgentPools().createOrUpdateAsync( resourceGroupName(), name(), agentPool.name(), agentPool.getAgentPoolInner()) .then(context.voidMono())); } innerModel().agentPoolProfiles().add(agentPool.innerModel()); return this; } @Override public KubernetesClusterImpl withAutoScalerProfile(ManagedClusterPropertiesAutoScalerProfile autoScalerProfile) { this.innerModel().withAutoScalerProfile(autoScalerProfile); return this; } @Override public KubernetesClusterImpl enablePrivateCluster() { if (innerModel().apiServerAccessProfile() == null) { innerModel().withApiServerAccessProfile(new ManagedClusterApiServerAccessProfile()); } innerModel().apiServerAccessProfile().withEnablePrivateCluster(true); return this; } @Override public PagedIterable<PrivateLinkResource> listPrivateLinkResources() { return new PagedIterable<>(listPrivateLinkResourcesAsync()); } @Override public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() { Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getPrivateLinkResources() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateLinkResourceImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() { return new PagedIterable<>(listPrivateEndpointConnectionsAsync()); } @Override public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() { Mono<Response<List<PrivateEndpointConnection>>> retList = this.manager().serviceClient() .getPrivateEndpointConnections() .listWithResponseAsync(this.resourceGroupName(), this.name()) .map(response -> new SimpleResponse<>(response, response.getValue().value().stream() .map(PrivateEndpointConnectionImpl::new) .collect(Collectors.toList()))); return PagedConverter.convertListToPagedFlux(retList); } @Override public KubernetesClusterImpl withAzureActiveDirectoryGroup(String activeDirectoryGroupObjectId) { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } if (innerModel().aadProfile().adminGroupObjectIDs() == null) { innerModel().aadProfile().withAdminGroupObjectIDs(new ArrayList<>()); } innerModel().aadProfile().adminGroupObjectIDs().add(activeDirectoryGroupObjectId); return this; } @Override public KubernetesClusterImpl enableAzureRbac() { this.withRBACEnabled(); if (innerModel().aadProfile() == null) { innerModel().withAadProfile(new ManagedClusterAadProfile().withManaged(true)); } innerModel().aadProfile().withEnableAzureRbac(true); return this; } @Override public KubernetesClusterImpl enableLocalAccounts() { innerModel().withDisableLocalAccounts(false); return this; } @Override public KubernetesClusterImpl disableLocalAccounts() { innerModel().withDisableLocalAccounts(true); return this; } @Override public KubernetesClusterImpl disableKubernetesRbac() { this.innerModel().withEnableRbac(false); return this; } @Override public KubernetesClusterImpl withDiskEncryptionSet(String diskEncryptionSetId) { this.innerModel().withDiskEncryptionSetId(diskEncryptionSetId); return this; } @Override public KubernetesClusterImpl withAgentPoolResourceGroup(String resourceGroupName) { this.innerModel().withNodeResourceGroup(resourceGroupName); return this; } @Override public KubernetesClusterImpl enablePublicNetworkAccess() { this.innerModel().withPublicNetworkAccess(PublicNetworkAccess.ENABLED); return this; } @Override public KubernetesClusterImpl disablePublicNetworkAccess() { this.innerModel().withPublicNetworkAccess(PublicNetworkAccess.DISABLED); return this; } private static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final PrivateLinkResourceInner innerModel; private PrivateLinkResourceImpl(PrivateLinkResourceInner innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.emptyList(); } } private static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final PrivateEndpointConnectionInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; private PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status().toString()), innerModel.privateLinkServiceConnectionState().description(), ""); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState().toString()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
simplify your resource in AKS test, you don't need all these configure. a simple one would do https://github.com/Azure/azure-sdk-for-java/blob/5b6d47ec83296d5a2e4ac539740eea5f3b008791/sdk/resourcemanager/azure-resourcemanager-containerservice/src/test/java/com/azure/resourcemanager/containerservice/KubernetesClustersTests.java#L365-L379
public void canCreateKubernetesClusterWithDisablePublicNetworkAccess() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolResourceGroupName = generateRandomResourceName("pool", 15); KubernetesCluster kubernetesCluster = containerServiceManager .kubernetesClusters() .define(aksName) .withRegion(Region.US_WEST2) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) .withAgentPoolVirtualMachineCount(1) .withOSDiskSizeInGB(30) .withOSDiskType(OSDiskType.EPHEMERAL) .withKubeletDiskType(KubeletDiskType.TEMPORARY) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withTag("pool.name", agentPoolName) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withTag("pool.name", agentPoolName1) .attach() .withDnsPrefix("mp1" + dnsPrefix) .withTag("tag1", "value1") .withAgentPoolResourceGroup(agentPoolResourceGroupName) .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, kubernetesCluster.publicNetworkAccess()); }
KubernetesCluster kubernetesCluster =
public void canCreateKubernetesClusterWithDisablePublicNetworkAccess() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix("mp1" + dnsPrefix) .disablePublicNetworkAccess() .create(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, kubernetesCluster.publicNetworkAccess()); }
class KubernetesClustersTests extends ContainerServiceManagementTest { private static final String SSH_KEY = sshPublicKey(); @Test public void canCRUDKubernetesCluster() { Context context = new Context( AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders().set("EnableACRTeleport", "true")); String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolName2 = generateRandomResourceName("ap2", 10); String agentPoolResourceGroupName = generateRandomResourceName("pool", 15); /* KubeletDiskType requires registering following preview feature: azure.features().register("Microsoft.ContainerService", "KubeletDisk"); */ KubernetesCluster kubernetesCluster = containerServiceManager .kubernetesClusters() .define(aksName) .withRegion(Region.US_WEST2) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) .withAgentPoolVirtualMachineCount(1) .withOSDiskSizeInGB(30) .withOSDiskType(OSDiskType.EPHEMERAL) .withKubeletDiskType(KubeletDiskType.TEMPORARY) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withTag("pool.name", agentPoolName) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withTag("pool.name", agentPoolName1) .attach() .withDnsPrefix("mp1" + dnsPrefix) .withTag("tag1", "value1") .withAgentPoolResourceGroup(agentPoolResourceGroupName) .create(context); Assertions.assertNotNull(kubernetesCluster.id()); Assertions.assertEquals(Region.US_WEST2, kubernetesCluster.region()); Assertions.assertEquals("testaks", kubernetesCluster.linuxRootUsername()); Assertions.assertEquals(2, kubernetesCluster.agentPools().size()); Assertions.assertEquals(agentPoolResourceGroupName, kubernetesCluster.agentPoolResourceGroup()); Assertions.assertEquals(agentPoolResourceGroupName, resourceManager.resourceGroups().getByName(agentPoolResourceGroupName).name()); KubernetesClusterAgentPool agentPool = kubernetesCluster.agentPools().get(agentPoolName); Assertions.assertNotNull(agentPool); Assertions.assertEquals(1, agentPool.count()); Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_F4S_V2, agentPool.vmSize()); Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, agentPool.type()); Assertions.assertEquals(AgentPoolMode.SYSTEM, agentPool.mode()); Assertions.assertEquals(OSDiskType.EPHEMERAL, agentPool.osDiskType()); Assertions.assertEquals(30, agentPool.osDiskSizeInGB()); Assertions.assertEquals(KubeletDiskType.TEMPORARY, agentPool.kubeletDiskType()); Assertions.assertEquals(Collections.singletonMap("pool.name", agentPoolName), agentPool.tags()); agentPool = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertNotNull(agentPool); Assertions.assertEquals(1, agentPool.count()); Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_A2_V2, agentPool.vmSize()); Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, agentPool.type()); Assertions.assertEquals(Collections.singletonMap("pool.name", agentPoolName1), agentPool.tags()); Assertions.assertNotNull(kubernetesCluster.tags().get("tag1")); kubernetesCluster.stop(); kubernetesCluster.refresh(); Assertions.assertEquals(Code.STOPPED, kubernetesCluster.powerState().code()); kubernetesCluster.start(); kubernetesCluster.refresh(); Assertions.assertEquals(Code.RUNNING, kubernetesCluster.powerState().code()); Map<String, String> nodeLables = new HashMap<>(2); nodeLables.put("environment", "dev"); nodeLables.put("app.1", "spring"); List<String> nodeTaints = new ArrayList<>(1); nodeTaints.add("key=value:NoSchedule"); kubernetesCluster = kubernetesCluster .update() .updateAgentPool(agentPoolName1) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withAgentPoolVirtualMachineCount(2) .withKubeletDiskType(KubeletDiskType.OS) .withoutTag("pool.name") .withTags(Collections.singletonMap("state", "updated")) .parent() .defineAgentPool(agentPoolName2) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) .withAgentPoolVirtualMachineCount(1) .withOSDiskSizeInGB(30) .withAgentPoolMode(AgentPoolMode.USER) .withOSDiskType(OSDiskType.MANAGED) .withKubeletDiskType(KubeletDiskType.TEMPORARY) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withNodeLabels(Collections.unmodifiableMap(nodeLables)) .withNodeTaints(Collections.unmodifiableList(nodeTaints)) .withTags(Collections.singletonMap("state", "created")) .attach() .withTag("tag2", "value2") .withTag("tag3", "value3") .withoutTag("tag1") .apply(context); Assertions.assertEquals(3, kubernetesCluster.agentPools().size()); agentPool = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertEquals(2, agentPool.count()); Assertions.assertEquals(AgentPoolMode.SYSTEM, agentPool.mode()); Assertions.assertEquals(KubeletDiskType.OS, agentPool.kubeletDiskType()); Assertions.assertEquals(Collections.singletonMap("state", "updated"), agentPool.tags()); agentPool = kubernetesCluster.agentPools().get(agentPoolName2); Assertions.assertNotNull(agentPool); Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_F4S_V2, agentPool.vmSize()); Assertions.assertEquals(1, agentPool.count()); Assertions.assertEquals(OSDiskType.MANAGED, agentPool.osDiskType()); Assertions.assertEquals(30, agentPool.osDiskSizeInGB()); Assertions.assertEquals(KubeletDiskType.TEMPORARY, agentPool.kubeletDiskType()); Assertions.assertEquals(Collections.singletonMap("state", "created"), agentPool.tags()); Assertions.assertEquals(Collections.unmodifiableMap(nodeLables), agentPool.nodeLabels()); Assertions.assertEquals("key=value:NoSchedule", agentPool.nodeTaints().iterator().next()); Assertions.assertEquals("value2", kubernetesCluster.tags().get("tag2")); Assertions.assertFalse(kubernetesCluster.tags().containsKey("tag1")); } @Test public void canAutoScaleKubernetesCluster() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolName2 = generateRandomResourceName("ap2", 10); String agentPoolName3 = generateRandomResourceName("ap2", 10); Map<String, String> nodeLables = new HashMap<>(2); nodeLables.put("environment", "dev"); nodeLables.put("app.1", "spring"); List<String> nodeTaints = new ArrayList<>(1); nodeTaints.add("key=value:NoSchedule"); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(3) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withAvailabilityZones(1, 2, 3) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withAutoScaling(1, 3) .withNodeLabels(Collections.unmodifiableMap(nodeLables)) .withNodeTaints(Collections.unmodifiableList(nodeTaints)) .attach() .defineAgentPool(agentPoolName2) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(0) .withMaxPodsCount(10) .attach() .withDnsPrefix("mp1" + dnsPrefix) .withAutoScalerProfile(new ManagedClusterPropertiesAutoScalerProfile().withScanInterval("30s")) .create(); System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); Assertions.assertEquals(Code.RUNNING, kubernetesCluster.powerState().code()); KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName); Assertions.assertEquals(3, agentPoolProfile.nodeSize()); Assertions.assertFalse(agentPoolProfile.isAutoScalingEnabled()); Assertions.assertEquals(Arrays.asList("1", "2", "3"), agentPoolProfile.availabilityZones()); Assertions.assertEquals(Code.RUNNING, agentPoolProfile.powerState().code()); KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertEquals(1, agentPoolProfile1.nodeSize()); Assertions.assertTrue(agentPoolProfile1.isAutoScalingEnabled()); Assertions.assertEquals(1, agentPoolProfile1.minimumNodeSize()); Assertions.assertEquals(3, agentPoolProfile1.maximumNodeSize()); Assertions.assertEquals(Collections.unmodifiableMap(nodeLables), agentPoolProfile1.nodeLabels()); Assertions.assertEquals("key=value:NoSchedule", agentPoolProfile1.nodeTaints().iterator().next()); KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2); Assertions.assertEquals(0, agentPoolProfile2.nodeSize()); Assertions.assertEquals(10, agentPoolProfile2.maximumPodsPerNode()); kubernetesCluster.update() .updateAgentPool(agentPoolName1) .withoutAutoScaling() .parent() .apply(); Assertions.assertFalse(agentPoolProfile1.isAutoScalingEnabled()); kubernetesCluster.update() .withoutAgentPool(agentPoolName1) .withoutAgentPool(agentPoolName2) .defineAgentPool(agentPoolName3) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(0) .attach() .apply(); Assertions.assertEquals(2, kubernetesCluster.agentPools().size()); KubernetesClusterAgentPool agentPoolProfile3 = kubernetesCluster.agentPools().get(agentPoolName3); Assertions.assertEquals(0, agentPoolProfile3.nodeSize()); } @Test public void canCreateClusterWithSpotVM() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolName2 = generateRandomResourceName("ap2", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withSpotPriorityVirtualMachine() .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName); Assertions.assertTrue(agentPoolProfile.virtualMachinePriority() == null || agentPoolProfile.virtualMachinePriority() == ScaleSetPriority.REGULAR); KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile1.virtualMachinePriority()); Assertions.assertEquals(ScaleSetEvictionPolicy.DELETE, agentPoolProfile1.virtualMachineEvictionPolicy()); Assertions.assertEquals(-1.0, agentPoolProfile1.virtualMachineMaximumPrice()); kubernetesCluster.update() .defineAgentPool(agentPoolName2) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withSpotPriorityVirtualMachine(ScaleSetEvictionPolicy.DEALLOCATE) .withVirtualMachineMaximumPrice(100.0) .attach() .apply(); KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2); Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile2.virtualMachinePriority()); Assertions.assertEquals(ScaleSetEvictionPolicy.DEALLOCATE, agentPoolProfile2.virtualMachineEvictionPolicy()); Assertions.assertEquals(100.0, agentPoolProfile2.virtualMachineMaximumPrice()); } @Test public void canListKubeConfigWithFormat() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); List<CredentialResult> results = kubernetesCluster.userKubeConfigs(Format.AZURE); Assertions.assertFalse(CoreUtils.isNullOrEmpty(results)); results = kubernetesCluster.userKubeConfigs(null); Assertions.assertFalse(CoreUtils.isNullOrEmpty(results)); byte[] kubeConfigContent1 = kubernetesCluster.userKubeConfigContent(null); Assertions.assertTrue(kubeConfigContent1 != null && kubeConfigContent1.length > 0); byte[] kubeConfigContent2 = kubernetesCluster.userKubeConfigContent(Format.AZURE); Assertions.assertTrue(kubeConfigContent2 != null && kubeConfigContent2.length > 0); byte[] kubeConfigContent3 = kubernetesCluster.userKubeConfigContent(Format.EXEC); Assertions.assertTrue(kubeConfigContent3 != null && kubeConfigContent3.length > 0); Assertions.assertArrayEquals(kubeConfigContent1, kubeConfigContent2); Assertions.assertArrayEquals(kubeConfigContent1, kubeConfigContent3); } @Test public void testKubernetesClusterAzureRbac() { final String aksName = generateRandomResourceName("aks", 15); final String dnsPrefix = generateRandomResourceName("dns", 10); final String agentPoolName = generateRandomResourceName("ap0", 10); KubernetesCluster kubernetesCluster = containerServiceManager .kubernetesClusters() .define(aksName) .withRegion(Region.US_WEST3) .withExistingResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .enableAzureRbac() .disableLocalAccounts() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) .withAgentPoolVirtualMachineCount(1) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withOSDiskSizeInGB(30) .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); Assertions.assertEquals(0, kubernetesCluster.azureActiveDirectoryGroupIds().size()); Assertions.assertFalse(kubernetesCluster.isLocalAccountsEnabled()); Assertions.assertTrue(kubernetesCluster.isAzureRbacEnabled()); Assertions.assertTrue(kubernetesCluster.enableRBAC()); } @Test public void canListOrchestrators() { List<OrchestratorVersionProfile> profiles = containerServiceManager.kubernetesClusters() .listOrchestrators(Region.US_WEST3, ContainerServiceResourceTypes.MANAGED_CLUSTERS) .stream().collect(Collectors.toList()); Assertions.assertFalse(profiles.isEmpty()); Assertions.assertEquals("Kubernetes", profiles.iterator().next().orchestratorType()); } @Test public void testBeginCreateAgentPool() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); Accepted<AgentPool> acceptedAgentPool = kubernetesCluster.beginCreateAgentPool(agentPoolName1, new AgentPoolData() .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.USER) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1)); ActivationResponse<AgentPool> activationResponse = acceptedAgentPool.getActivationResponse(); Assertions.assertEquals("Creating", activationResponse.getStatus().toString()); Assertions.assertEquals("Creating", activationResponse.getValue().provisioningState()); Assertions.assertEquals(agentPoolName1, activationResponse.getValue().name()); Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, activationResponse.getValue().type()); Assertions.assertEquals(AgentPoolMode.USER, activationResponse.getValue().mode()); Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_A2_V2, activationResponse.getValue().vmSize()); Assertions.assertEquals(1, activationResponse.getValue().count()); AgentPool agentPool = acceptedAgentPool.getFinalResult(); Assertions.assertEquals("Succeeded", agentPool.provisioningState()); Assertions.assertEquals(agentPoolName1, agentPool.name()); } @Test public void testFipsEnabled() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolName2 = generateRandomResourceName("ap2", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.USER) .withFipsEnabled() .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); Assertions.assertFalse(kubernetesCluster.agentPools().get(agentPoolName).isFipsEnabled()); Assertions.assertTrue(kubernetesCluster.agentPools().get(agentPoolName1).isFipsEnabled()); AgentPoolData request = new AgentPoolData() .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.USER) .withFipsEnabled(); AgentPool agentPool3 = kubernetesCluster.beginCreateAgentPool(agentPoolName2, request).getFinalResult(); Assertions.assertTrue(agentPool3.isFipsEnabled()); kubernetesCluster.refresh(); Assertions.assertTrue(kubernetesCluster.agentPools().get(agentPoolName2).isFipsEnabled()); } @Test public void canCreateClusterWithDefaultVersion() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() .define(generateRandomResourceName("aks", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(generateRandomResourceName("ap", 15)) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(generateRandomResourceName("dns", 15)) .create(); kubernetesCluster.refresh(); Assertions.assertNotNull(kubernetesCluster.version()); } @Test public void testUpdateKubernetesVersion() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() .define(generateRandomResourceName("aks", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withVersion("1.27.9") .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(generateRandomResourceName("ap", 15)) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(generateRandomResourceName("dns", 15)) .create(); kubernetesCluster.refresh(); Assertions.assertEquals("1.27.9", kubernetesCluster.version()); kubernetesCluster.update().withVersion("1.28.5").apply(); kubernetesCluster.refresh(); Assertions.assertEquals("1.28.5", kubernetesCluster.version()); } @Test public void testUpdateManagedClusterSkuAndKubernetesSupportPlan() { String aksName = generateRandomResourceName("aks", 15); resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() .define(aksName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(generateRandomResourceName("ap", 15)) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(generateRandomResourceName("dns", 15)) .create(); kubernetesCluster.update().withPremiumSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.PREMIUM, kubernetesCluster.sku().tier()); Assertions.assertEquals(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT, kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withStandardSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.STANDARD, kubernetesCluster.sku().tier()); Assertions.assertEquals(KubernetesSupportPlan.KUBERNETES_OFFICIAL, kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withPremiumSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.PREMIUM, kubernetesCluster.sku().tier()); Assertions.assertEquals(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT, kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withFreeSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.FREE, kubernetesCluster.sku().tier()); Assertions.assertEquals(KubernetesSupportPlan.KUBERNETES_OFFICIAL, kubernetesCluster.innerModel().supportPlan()); } @Test @Test public void canUpdatePublicNetworkAccess() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolResourceGroupName = generateRandomResourceName("pool", 15); KubernetesCluster kubernetesCluster = containerServiceManager .kubernetesClusters() .define(aksName) .withRegion(Region.US_WEST2) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) .withAgentPoolVirtualMachineCount(1) .withOSDiskSizeInGB(30) .withOSDiskType(OSDiskType.EPHEMERAL) .withKubeletDiskType(KubeletDiskType.TEMPORARY) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withTag("pool.name", agentPoolName) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withTag("pool.name", agentPoolName1) .attach() .withDnsPrefix("mp1" + dnsPrefix) .withTag("tag1", "value1") .withAgentPoolResourceGroup(agentPoolResourceGroupName) .create(); kubernetesCluster.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, kubernetesCluster.publicNetworkAccess()); kubernetesCluster.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, kubernetesCluster.publicNetworkAccess()); } }
class KubernetesClustersTests extends ContainerServiceManagementTest { private static final String SSH_KEY = sshPublicKey(); @Test public void canCRUDKubernetesCluster() { Context context = new Context( AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders().set("EnableACRTeleport", "true")); String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolName2 = generateRandomResourceName("ap2", 10); String agentPoolResourceGroupName = generateRandomResourceName("pool", 15); /* KubeletDiskType requires registering following preview feature: azure.features().register("Microsoft.ContainerService", "KubeletDisk"); */ KubernetesCluster kubernetesCluster = containerServiceManager .kubernetesClusters() .define(aksName) .withRegion(Region.US_WEST2) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) .withAgentPoolVirtualMachineCount(1) .withOSDiskSizeInGB(30) .withOSDiskType(OSDiskType.EPHEMERAL) .withKubeletDiskType(KubeletDiskType.TEMPORARY) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withTag("pool.name", agentPoolName) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withTag("pool.name", agentPoolName1) .attach() .withDnsPrefix("mp1" + dnsPrefix) .withTag("tag1", "value1") .withAgentPoolResourceGroup(agentPoolResourceGroupName) .create(context); Assertions.assertNotNull(kubernetesCluster.id()); Assertions.assertEquals(Region.US_WEST2, kubernetesCluster.region()); Assertions.assertEquals("testaks", kubernetesCluster.linuxRootUsername()); Assertions.assertEquals(2, kubernetesCluster.agentPools().size()); Assertions.assertEquals(agentPoolResourceGroupName, kubernetesCluster.agentPoolResourceGroup()); Assertions.assertEquals(agentPoolResourceGroupName, resourceManager.resourceGroups().getByName(agentPoolResourceGroupName).name()); KubernetesClusterAgentPool agentPool = kubernetesCluster.agentPools().get(agentPoolName); Assertions.assertNotNull(agentPool); Assertions.assertEquals(1, agentPool.count()); Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_F4S_V2, agentPool.vmSize()); Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, agentPool.type()); Assertions.assertEquals(AgentPoolMode.SYSTEM, agentPool.mode()); Assertions.assertEquals(OSDiskType.EPHEMERAL, agentPool.osDiskType()); Assertions.assertEquals(30, agentPool.osDiskSizeInGB()); Assertions.assertEquals(KubeletDiskType.TEMPORARY, agentPool.kubeletDiskType()); Assertions.assertEquals(Collections.singletonMap("pool.name", agentPoolName), agentPool.tags()); agentPool = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertNotNull(agentPool); Assertions.assertEquals(1, agentPool.count()); Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_A2_V2, agentPool.vmSize()); Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, agentPool.type()); Assertions.assertEquals(Collections.singletonMap("pool.name", agentPoolName1), agentPool.tags()); Assertions.assertNotNull(kubernetesCluster.tags().get("tag1")); kubernetesCluster.stop(); kubernetesCluster.refresh(); Assertions.assertEquals(Code.STOPPED, kubernetesCluster.powerState().code()); kubernetesCluster.start(); kubernetesCluster.refresh(); Assertions.assertEquals(Code.RUNNING, kubernetesCluster.powerState().code()); Map<String, String> nodeLables = new HashMap<>(2); nodeLables.put("environment", "dev"); nodeLables.put("app.1", "spring"); List<String> nodeTaints = new ArrayList<>(1); nodeTaints.add("key=value:NoSchedule"); kubernetesCluster = kubernetesCluster .update() .updateAgentPool(agentPoolName1) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withAgentPoolVirtualMachineCount(2) .withKubeletDiskType(KubeletDiskType.OS) .withoutTag("pool.name") .withTags(Collections.singletonMap("state", "updated")) .parent() .defineAgentPool(agentPoolName2) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_F4S_V2) .withAgentPoolVirtualMachineCount(1) .withOSDiskSizeInGB(30) .withAgentPoolMode(AgentPoolMode.USER) .withOSDiskType(OSDiskType.MANAGED) .withKubeletDiskType(KubeletDiskType.TEMPORARY) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withNodeLabels(Collections.unmodifiableMap(nodeLables)) .withNodeTaints(Collections.unmodifiableList(nodeTaints)) .withTags(Collections.singletonMap("state", "created")) .attach() .withTag("tag2", "value2") .withTag("tag3", "value3") .withoutTag("tag1") .apply(context); Assertions.assertEquals(3, kubernetesCluster.agentPools().size()); agentPool = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertEquals(2, agentPool.count()); Assertions.assertEquals(AgentPoolMode.SYSTEM, agentPool.mode()); Assertions.assertEquals(KubeletDiskType.OS, agentPool.kubeletDiskType()); Assertions.assertEquals(Collections.singletonMap("state", "updated"), agentPool.tags()); agentPool = kubernetesCluster.agentPools().get(agentPoolName2); Assertions.assertNotNull(agentPool); Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_F4S_V2, agentPool.vmSize()); Assertions.assertEquals(1, agentPool.count()); Assertions.assertEquals(OSDiskType.MANAGED, agentPool.osDiskType()); Assertions.assertEquals(30, agentPool.osDiskSizeInGB()); Assertions.assertEquals(KubeletDiskType.TEMPORARY, agentPool.kubeletDiskType()); Assertions.assertEquals(Collections.singletonMap("state", "created"), agentPool.tags()); Assertions.assertEquals(Collections.unmodifiableMap(nodeLables), agentPool.nodeLabels()); Assertions.assertEquals("key=value:NoSchedule", agentPool.nodeTaints().iterator().next()); Assertions.assertEquals("value2", kubernetesCluster.tags().get("tag2")); Assertions.assertFalse(kubernetesCluster.tags().containsKey("tag1")); } @Test public void canAutoScaleKubernetesCluster() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolName2 = generateRandomResourceName("ap2", 10); String agentPoolName3 = generateRandomResourceName("ap2", 10); Map<String, String> nodeLables = new HashMap<>(2); nodeLables.put("environment", "dev"); nodeLables.put("app.1", "spring"); List<String> nodeTaints = new ArrayList<>(1); nodeTaints.add("key=value:NoSchedule"); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(3) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withAvailabilityZones(1, 2, 3) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withAutoScaling(1, 3) .withNodeLabels(Collections.unmodifiableMap(nodeLables)) .withNodeTaints(Collections.unmodifiableList(nodeTaints)) .attach() .defineAgentPool(agentPoolName2) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(0) .withMaxPodsCount(10) .attach() .withDnsPrefix("mp1" + dnsPrefix) .withAutoScalerProfile(new ManagedClusterPropertiesAutoScalerProfile().withScanInterval("30s")) .create(); System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); Assertions.assertEquals(Code.RUNNING, kubernetesCluster.powerState().code()); KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName); Assertions.assertEquals(3, agentPoolProfile.nodeSize()); Assertions.assertFalse(agentPoolProfile.isAutoScalingEnabled()); Assertions.assertEquals(Arrays.asList("1", "2", "3"), agentPoolProfile.availabilityZones()); Assertions.assertEquals(Code.RUNNING, agentPoolProfile.powerState().code()); KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertEquals(1, agentPoolProfile1.nodeSize()); Assertions.assertTrue(agentPoolProfile1.isAutoScalingEnabled()); Assertions.assertEquals(1, agentPoolProfile1.minimumNodeSize()); Assertions.assertEquals(3, agentPoolProfile1.maximumNodeSize()); Assertions.assertEquals(Collections.unmodifiableMap(nodeLables), agentPoolProfile1.nodeLabels()); Assertions.assertEquals("key=value:NoSchedule", agentPoolProfile1.nodeTaints().iterator().next()); KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2); Assertions.assertEquals(0, agentPoolProfile2.nodeSize()); Assertions.assertEquals(10, agentPoolProfile2.maximumPodsPerNode()); kubernetesCluster.update() .updateAgentPool(agentPoolName1) .withoutAutoScaling() .parent() .apply(); Assertions.assertFalse(agentPoolProfile1.isAutoScalingEnabled()); kubernetesCluster.update() .withoutAgentPool(agentPoolName1) .withoutAgentPool(agentPoolName2) .defineAgentPool(agentPoolName3) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(0) .attach() .apply(); Assertions.assertEquals(2, kubernetesCluster.agentPools().size()); KubernetesClusterAgentPool agentPoolProfile3 = kubernetesCluster.agentPools().get(agentPoolName3); Assertions.assertEquals(0, agentPoolProfile3.nodeSize()); } @Test public void canCreateClusterWithSpotVM() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolName2 = generateRandomResourceName("ap2", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withSpotPriorityVirtualMachine() .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8)); KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName); Assertions.assertTrue(agentPoolProfile.virtualMachinePriority() == null || agentPoolProfile.virtualMachinePriority() == ScaleSetPriority.REGULAR); KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1); Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile1.virtualMachinePriority()); Assertions.assertEquals(ScaleSetEvictionPolicy.DELETE, agentPoolProfile1.virtualMachineEvictionPolicy()); Assertions.assertEquals(-1.0, agentPoolProfile1.virtualMachineMaximumPrice()); kubernetesCluster.update() .defineAgentPool(agentPoolName2) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1) .withSpotPriorityVirtualMachine(ScaleSetEvictionPolicy.DEALLOCATE) .withVirtualMachineMaximumPrice(100.0) .attach() .apply(); KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2); Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile2.virtualMachinePriority()); Assertions.assertEquals(ScaleSetEvictionPolicy.DEALLOCATE, agentPoolProfile2.virtualMachineEvictionPolicy()); Assertions.assertEquals(100.0, agentPoolProfile2.virtualMachineMaximumPrice()); } @Test public void canListKubeConfigWithFormat() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); List<CredentialResult> results = kubernetesCluster.userKubeConfigs(Format.AZURE); Assertions.assertFalse(CoreUtils.isNullOrEmpty(results)); results = kubernetesCluster.userKubeConfigs(null); Assertions.assertFalse(CoreUtils.isNullOrEmpty(results)); byte[] kubeConfigContent1 = kubernetesCluster.userKubeConfigContent(null); Assertions.assertTrue(kubeConfigContent1 != null && kubeConfigContent1.length > 0); byte[] kubeConfigContent2 = kubernetesCluster.userKubeConfigContent(Format.AZURE); Assertions.assertTrue(kubeConfigContent2 != null && kubeConfigContent2.length > 0); byte[] kubeConfigContent3 = kubernetesCluster.userKubeConfigContent(Format.EXEC); Assertions.assertTrue(kubeConfigContent3 != null && kubeConfigContent3.length > 0); Assertions.assertArrayEquals(kubeConfigContent1, kubeConfigContent2); Assertions.assertArrayEquals(kubeConfigContent1, kubeConfigContent3); } @Test public void testKubernetesClusterAzureRbac() { final String aksName = generateRandomResourceName("aks", 15); final String dnsPrefix = generateRandomResourceName("dns", 10); final String agentPoolName = generateRandomResourceName("ap0", 10); KubernetesCluster kubernetesCluster = containerServiceManager .kubernetesClusters() .define(aksName) .withRegion(Region.US_WEST3) .withExistingResourceGroup(rgName) .withDefaultVersion() .withSystemAssignedManagedServiceIdentity() .enableAzureRbac() .disableLocalAccounts() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V3) .withAgentPoolVirtualMachineCount(1) .withAgentPoolMode(AgentPoolMode.SYSTEM) .withOSDiskSizeInGB(30) .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); Assertions.assertEquals(0, kubernetesCluster.azureActiveDirectoryGroupIds().size()); Assertions.assertFalse(kubernetesCluster.isLocalAccountsEnabled()); Assertions.assertTrue(kubernetesCluster.isAzureRbacEnabled()); Assertions.assertTrue(kubernetesCluster.enableRBAC()); } @Test public void canListOrchestrators() { List<OrchestratorVersionProfile> profiles = containerServiceManager.kubernetesClusters() .listOrchestrators(Region.US_WEST3, ContainerServiceResourceTypes.MANAGED_CLUSTERS) .stream().collect(Collectors.toList()); Assertions.assertFalse(profiles.isEmpty()); Assertions.assertEquals("Kubernetes", profiles.iterator().next().orchestratorType()); } @Test public void testBeginCreateAgentPool() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); Accepted<AgentPool> acceptedAgentPool = kubernetesCluster.beginCreateAgentPool(agentPoolName1, new AgentPoolData() .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.USER) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2) .withAgentPoolVirtualMachineCount(1)); ActivationResponse<AgentPool> activationResponse = acceptedAgentPool.getActivationResponse(); Assertions.assertEquals("Creating", activationResponse.getStatus().toString()); Assertions.assertEquals("Creating", activationResponse.getValue().provisioningState()); Assertions.assertEquals(agentPoolName1, activationResponse.getValue().name()); Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, activationResponse.getValue().type()); Assertions.assertEquals(AgentPoolMode.USER, activationResponse.getValue().mode()); Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_A2_V2, activationResponse.getValue().vmSize()); Assertions.assertEquals(1, activationResponse.getValue().count()); AgentPool agentPool = acceptedAgentPool.getFinalResult(); Assertions.assertEquals("Succeeded", agentPool.provisioningState()); Assertions.assertEquals(agentPoolName1, agentPool.name()); } @Test public void testFipsEnabled() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); String agentPoolName1 = generateRandomResourceName("ap1", 10); String agentPoolName2 = generateRandomResourceName("ap2", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .defineAgentPool(agentPoolName1) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.USER) .withFipsEnabled() .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); Assertions.assertFalse(kubernetesCluster.agentPools().get(agentPoolName).isFipsEnabled()); Assertions.assertTrue(kubernetesCluster.agentPools().get(agentPoolName1).isFipsEnabled()); AgentPoolData request = new AgentPoolData() .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.USER) .withFipsEnabled(); AgentPool agentPool3 = kubernetesCluster.beginCreateAgentPool(agentPoolName2, request).getFinalResult(); Assertions.assertTrue(agentPool3.isFipsEnabled()); kubernetesCluster.refresh(); Assertions.assertTrue(kubernetesCluster.agentPools().get(agentPoolName2).isFipsEnabled()); } @Test public void canCreateClusterWithDefaultVersion() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() .define(generateRandomResourceName("aks", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(generateRandomResourceName("ap", 15)) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(generateRandomResourceName("dns", 15)) .create(); kubernetesCluster.refresh(); Assertions.assertNotNull(kubernetesCluster.version()); } @Test public void testUpdateKubernetesVersion() { resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() .define(generateRandomResourceName("aks", 15)) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withVersion("1.27.9") .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(generateRandomResourceName("ap", 15)) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(generateRandomResourceName("dns", 15)) .create(); kubernetesCluster.refresh(); Assertions.assertEquals("1.27.9", kubernetesCluster.version()); kubernetesCluster.update().withVersion("1.28.5").apply(); kubernetesCluster.refresh(); Assertions.assertEquals("1.28.5", kubernetesCluster.version()); } @Test public void testUpdateManagedClusterSkuAndKubernetesSupportPlan() { String aksName = generateRandomResourceName("aks", 15); resourceManager.resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters() .define(aksName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(generateRandomResourceName("ap", 15)) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix(generateRandomResourceName("dns", 15)) .create(); kubernetesCluster.update().withPremiumSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.PREMIUM, kubernetesCluster.sku().tier()); Assertions.assertEquals(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT, kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withStandardSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.STANDARD, kubernetesCluster.sku().tier()); Assertions.assertEquals(KubernetesSupportPlan.KUBERNETES_OFFICIAL, kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withPremiumSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.PREMIUM, kubernetesCluster.sku().tier()); Assertions.assertEquals(KubernetesSupportPlan.AKSLONG_TERM_SUPPORT, kubernetesCluster.innerModel().supportPlan()); kubernetesCluster.update().withFreeSku().apply(); kubernetesCluster.refresh(); Assertions.assertEquals(ManagedClusterSkuTier.FREE, kubernetesCluster.sku().tier()); Assertions.assertEquals(KubernetesSupportPlan.KUBERNETES_OFFICIAL, kubernetesCluster.innerModel().supportPlan()); } @Test @Test public void canUpdatePublicNetworkAccess() { String aksName = generateRandomResourceName("aks", 15); String dnsPrefix = generateRandomResourceName("dns", 10); String agentPoolName = generateRandomResourceName("ap0", 10); KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withDefaultVersion() .withRootUsername("testaks") .withSshKey(SSH_KEY) .withSystemAssignedManagedServiceIdentity() .defineAgentPool(agentPoolName) .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) .withAgentPoolVirtualMachineCount(1) .withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS) .withAgentPoolMode(AgentPoolMode.SYSTEM) .attach() .withDnsPrefix("mp1" + dnsPrefix) .create(); kubernetesCluster.update().disablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.DISABLED, kubernetesCluster.publicNetworkAccess()); kubernetesCluster.update().enablePublicNetworkAccess().apply(); Assertions.assertEquals(PublicNetworkAccess.ENABLED, kubernetesCluster.publicNetworkAccess()); } }
No need to trim or check empty, just do `PublicNetworkAccess.fromString`, if not null.
public PublicNetworkAccess publicNetworkAccess() { return Objects.isNull(innerModel().publicNetworkAccess()) && innerModel().publicNetworkAccess().trim().isEmpty() ? null : PublicNetworkAccess.fromString(innerModel().publicNetworkAccess()); }
&& innerModel().publicNetworkAccess().trim().isEmpty() ? null : PublicNetworkAccess.fromString(innerModel().publicNetworkAccess());
public PublicNetworkAccess publicNetworkAccess() { return Objects.isNull(innerModel().publicNetworkAccess()) ? null : PublicNetworkAccess.fromString(innerModel().publicNetworkAccess()); }
class PipedInputStreamWithCallback extends PipedInputStream { private Runnable callback; private void addCallback(Runnable action) { this.callback = action; } @Override public void close() throws IOException { callback.run(); super.close(); } }
class PipedInputStreamWithCallback extends PipedInputStream { private Runnable callback; private void addCallback(Runnable action) { this.callback = action; } @Override public void close() throws IOException { callback.run(); super.close(); } }
this is very uncommon to throw in getter for null value, perhaps the null check and throwing should be moved to the type setter? (and/or to the code that calls the getter)
public String getType() { if (this.type == null) { this.type = this.jsonSerializable.getString(Constants.Properties.VECTOR_INDEX_TYPE); if (this.type == null) { throw new IllegalArgumentException("INVALID vectorIndexType of " + this.jsonSerializable.getString(Constants.Properties.VECTOR_INDEX_TYPE)); } } return this.type; }
throw new IllegalArgumentException("INVALID vectorIndexType of " + this.jsonSerializable.getString(Constants.Properties.VECTOR_INDEX_TYPE));
public String getType() { if (this.type == null) { this.type = this.jsonSerializable.getString(Constants.Properties.VECTOR_INDEX_TYPE); } return this.type; }
class CosmosVectorIndexSpec { private JsonSerializable jsonSerializable; private String type; /** * Constructor */ public CosmosVectorIndexSpec() { this.jsonSerializable = new JsonSerializable(); } /** * Gets path. * * @return the path. */ public String getPath() { return this.jsonSerializable.getString(Constants.Properties.PATH); } /** * Sets path. * * @param path the path. * @return the SpatialSpec. */ public CosmosVectorIndexSpec setPath(String path) { this.jsonSerializable.set(Constants.Properties.PATH, path, CosmosItemSerializer.DEFAULT_SERIALIZER); return this; } /** * Gets the vector index type for the vector index * * @return the vector index type */ /** * Sets the vector index type for the vector index * * @param type the vector index type * @return the VectorIndexSpec */ public CosmosVectorIndexSpec setType(String type) { this.type = type; this.jsonSerializable.set(Constants.Properties.VECTOR_INDEX_TYPE, this.type, CosmosItemSerializer.DEFAULT_SERIALIZER); return this; } void populatePropertyBag() { this.jsonSerializable.populatePropertyBag(); } JsonSerializable getJsonSerializable() { return this.jsonSerializable; } }
class CosmosVectorIndexSpec { private final JsonSerializable jsonSerializable; private String type; /** * Constructor */ public CosmosVectorIndexSpec() { this.jsonSerializable = new JsonSerializable(); } /** * Gets path. * * @return the path. */ public String getPath() { return this.jsonSerializable.getString(Constants.Properties.PATH); } /** * Sets path. * * @param path the path. * @return the SpatialSpec. */ public CosmosVectorIndexSpec setPath(String path) { this.jsonSerializable.set(Constants.Properties.PATH, path, CosmosItemSerializer.DEFAULT_SERIALIZER); return this; } /** * Gets the vector index type for the vector index * * @return the vector index type */ /** * Sets the vector index type for the vector index * * @param type the vector index type * @return the VectorIndexSpec */ public CosmosVectorIndexSpec setType(String type) { checkNotNull(type, "cosmosVectorIndexType cannot be null"); this.type = type; this.jsonSerializable.set(Constants.Properties.VECTOR_INDEX_TYPE, this.type, CosmosItemSerializer.DEFAULT_SERIALIZER); return this; } void populatePropertyBag() { this.jsonSerializable.populatePropertyBag(); } JsonSerializable getJsonSerializable() { return this.jsonSerializable; } }
Doesn't this result with end being called multiple times if there was an exception?
public BinaryData getBodyAsBinaryData() { try { return response.getBodyAsBinaryData(); } catch (Exception e) { tracer.end(null, e, span); throw e; } finally { endNoError(); } }
endNoError();
public BinaryData getBodyAsBinaryData() { try { return response.getBodyAsBinaryData(); } catch (Exception e) { onError(null, e); throw e; } finally { endNoError(); } }
class TraceableResponse extends HttpResponse { private final HttpResponse response; private final Context span; private final Tracer tracer; private TraceableResponse(HttpResponse response, Tracer tracer, Context span) { super(response.getRequest()); this.response = response; this.span = span; this.tracer = tracer; } public static HttpResponse create(HttpResponse response, Tracer tracer, Context span) { if (tracer.isRecording(span)) { return new TraceableResponse(response, tracer, span); } tracer.end(null, null, span); return response; } @Override public int getStatusCode() { return response.getStatusCode(); } @Deprecated @Override public String getHeaderValue(String name) { return response.getHeaderValue(name); } @Override public String getHeaderValue(HttpHeaderName headerName) { return response.getHeaderValue(headerName); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { return Flux.using(() -> span, s -> response.getBody() .doOnError(e -> tracer.end(null, e, s)) .doOnCancel(() -> tracer.end(CANCELLED_ERROR_TYPE, null, s)), s -> endNoError()); } @Override public Mono<byte[]> getBodyAsByteArray() { return endSpanWhen(response.getBodyAsByteArray()); } @Override public Mono<String> getBodyAsString() { return endSpanWhen(response.getBodyAsString()); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return endSpanWhen(response.getBodyAsString(charset)); } @Override public Mono<InputStream> getBodyAsInputStream() { return endSpanWhen(response.getBodyAsInputStream()); } @Override public void close() { response.close(); endNoError(); } private <T> Mono<T> endSpanWhen(Mono<T> publisher) { return Mono.using(() -> span, s -> publisher.doOnError(e -> tracer.end(null, e, s)) .doOnCancel(() -> tracer.end(CANCELLED_ERROR_TYPE, null, s)), s -> endNoError()); } private void endNoError() { String errorType = null; if (response == null) { errorType = OTHER_ERROR_TYPE; } else if (response.getStatusCode() >= 400) { errorType = String.valueOf(response.getStatusCode()); } tracer.end(errorType, null, span); } }
class TraceableResponse extends HttpResponse { private final HttpResponse response; private final Context span; private final Tracer tracer; private volatile int ended = 0; private static final AtomicIntegerFieldUpdater<TraceableResponse> ENDED_UPDATER = AtomicIntegerFieldUpdater.newUpdater(TraceableResponse.class, "ended"); private TraceableResponse(HttpResponse response, Tracer tracer, Context span) { super(response.getRequest()); this.response = response; this.span = span; this.tracer = tracer; } public static HttpResponse create(HttpResponse response, Tracer tracer, Context span) { if (tracer.isRecording(span)) { return new TraceableResponse(response, tracer, span); } tracer.end(null, null, span); return response; } @Override public int getStatusCode() { return response.getStatusCode(); } @Deprecated @Override public String getHeaderValue(String name) { return response.getHeaderValue(name); } @Override public String getHeaderValue(HttpHeaderName headerName) { return response.getHeaderValue(headerName); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { return Flux.using(() -> span, s -> response.getBody() .doOnError(e -> onError(null, e)) .doOnCancel(() -> onError(CANCELLED_ERROR_TYPE, null)), s -> endNoError()); } @Override public Mono<byte[]> getBodyAsByteArray() { return endSpanWhen(response.getBodyAsByteArray()); } @Override public Mono<String> getBodyAsString() { return endSpanWhen(response.getBodyAsString()); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return endSpanWhen(response.getBodyAsString(charset)); } @Override public Mono<InputStream> getBodyAsInputStream() { return endSpanWhen(response.getBodyAsInputStream()); } @Override public void close() { response.close(); endNoError(); } private <T> Mono<T> endSpanWhen(Mono<T> publisher) { return Mono.using(() -> span, s -> publisher.doOnError(e -> onError(null, e)).doOnCancel(() -> onError(CANCELLED_ERROR_TYPE, null)), s -> endNoError()); } private void onError(String errorType, Throwable error) { if (ENDED_UPDATER.compareAndSet(this, 0, 1)) { tracer.end(errorType, error, span); } } private void endNoError() { if (ENDED_UPDATER.compareAndSet(this, 0, 1)) { String errorType = null; if (response == null) { errorType = OTHER_ERROR_TYPE; } else if (response.getStatusCode() >= 400) { errorType = String.valueOf(response.getStatusCode()); } tracer.end(errorType, null, span); } } }
This could be another spot where multiple ends are called for the span if the body is consumed with a try-with-resource block closing the HttpResponse
public void close() { response.close(); endNoError(); }
endNoError();
public void close() { response.close(); endNoError(); }
class TraceableResponse extends HttpResponse { private final HttpResponse response; private final Context span; private final Tracer tracer; private TraceableResponse(HttpResponse response, Tracer tracer, Context span) { super(response.getRequest()); this.response = response; this.span = span; this.tracer = tracer; } public static HttpResponse create(HttpResponse response, Tracer tracer, Context span) { if (tracer.isRecording(span)) { return new TraceableResponse(response, tracer, span); } tracer.end(null, null, span); return response; } @Override public int getStatusCode() { return response.getStatusCode(); } @Deprecated @Override public String getHeaderValue(String name) { return response.getHeaderValue(name); } @Override public String getHeaderValue(HttpHeaderName headerName) { return response.getHeaderValue(headerName); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { return Flux.using(() -> span, s -> response.getBody() .doOnError(e -> tracer.end(null, e, s)) .doOnCancel(() -> tracer.end(CANCELLED_ERROR_TYPE, null, s)), s -> endNoError()); } @Override public Mono<byte[]> getBodyAsByteArray() { return endSpanWhen(response.getBodyAsByteArray()); } @Override public Mono<String> getBodyAsString() { return endSpanWhen(response.getBodyAsString()); } @Override public BinaryData getBodyAsBinaryData() { try { return response.getBodyAsBinaryData(); } catch (Exception e) { tracer.end(null, e, span); throw e; } finally { endNoError(); } } @Override public Mono<String> getBodyAsString(Charset charset) { return endSpanWhen(response.getBodyAsString(charset)); } @Override public Mono<InputStream> getBodyAsInputStream() { return endSpanWhen(response.getBodyAsInputStream()); } @Override private <T> Mono<T> endSpanWhen(Mono<T> publisher) { return Mono.using(() -> span, s -> publisher.doOnError(e -> tracer.end(null, e, s)) .doOnCancel(() -> tracer.end(CANCELLED_ERROR_TYPE, null, s)), s -> endNoError()); } private void endNoError() { String errorType = null; if (response == null) { errorType = OTHER_ERROR_TYPE; } else if (response.getStatusCode() >= 400) { errorType = String.valueOf(response.getStatusCode()); } tracer.end(errorType, null, span); } }
class TraceableResponse extends HttpResponse { private final HttpResponse response; private final Context span; private final Tracer tracer; private volatile int ended = 0; private static final AtomicIntegerFieldUpdater<TraceableResponse> ENDED_UPDATER = AtomicIntegerFieldUpdater.newUpdater(TraceableResponse.class, "ended"); private TraceableResponse(HttpResponse response, Tracer tracer, Context span) { super(response.getRequest()); this.response = response; this.span = span; this.tracer = tracer; } public static HttpResponse create(HttpResponse response, Tracer tracer, Context span) { if (tracer.isRecording(span)) { return new TraceableResponse(response, tracer, span); } tracer.end(null, null, span); return response; } @Override public int getStatusCode() { return response.getStatusCode(); } @Deprecated @Override public String getHeaderValue(String name) { return response.getHeaderValue(name); } @Override public String getHeaderValue(HttpHeaderName headerName) { return response.getHeaderValue(headerName); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { return Flux.using(() -> span, s -> response.getBody() .doOnError(e -> onError(null, e)) .doOnCancel(() -> onError(CANCELLED_ERROR_TYPE, null)), s -> endNoError()); } @Override public Mono<byte[]> getBodyAsByteArray() { return endSpanWhen(response.getBodyAsByteArray()); } @Override public Mono<String> getBodyAsString() { return endSpanWhen(response.getBodyAsString()); } @Override public BinaryData getBodyAsBinaryData() { try { return response.getBodyAsBinaryData(); } catch (Exception e) { onError(null, e); throw e; } finally { endNoError(); } } @Override public Mono<String> getBodyAsString(Charset charset) { return endSpanWhen(response.getBodyAsString(charset)); } @Override public Mono<InputStream> getBodyAsInputStream() { return endSpanWhen(response.getBodyAsInputStream()); } @Override private <T> Mono<T> endSpanWhen(Mono<T> publisher) { return Mono.using(() -> span, s -> publisher.doOnError(e -> onError(null, e)).doOnCancel(() -> onError(CANCELLED_ERROR_TYPE, null)), s -> endNoError()); } private void onError(String errorType, Throwable error) { if (ENDED_UPDATER.compareAndSet(this, 0, 1)) { tracer.end(errorType, error, span); } } private void endNoError() { if (ENDED_UPDATER.compareAndSet(this, 0, 1)) { String errorType = null; if (response == null) { errorType = OTHER_ERROR_TYPE; } else if (response.getStatusCode() >= 400) { errorType = String.valueOf(response.getStatusCode()); } tracer.end(errorType, null, span); } } }
it's ok to end span multiple times, but given it raises so much comment, I'll add checks :)
public BinaryData getBodyAsBinaryData() { try { return response.getBodyAsBinaryData(); } catch (Exception e) { tracer.end(null, e, span); throw e; } finally { endNoError(); } }
endNoError();
public BinaryData getBodyAsBinaryData() { try { return response.getBodyAsBinaryData(); } catch (Exception e) { onError(null, e); throw e; } finally { endNoError(); } }
class TraceableResponse extends HttpResponse { private final HttpResponse response; private final Context span; private final Tracer tracer; private TraceableResponse(HttpResponse response, Tracer tracer, Context span) { super(response.getRequest()); this.response = response; this.span = span; this.tracer = tracer; } public static HttpResponse create(HttpResponse response, Tracer tracer, Context span) { if (tracer.isRecording(span)) { return new TraceableResponse(response, tracer, span); } tracer.end(null, null, span); return response; } @Override public int getStatusCode() { return response.getStatusCode(); } @Deprecated @Override public String getHeaderValue(String name) { return response.getHeaderValue(name); } @Override public String getHeaderValue(HttpHeaderName headerName) { return response.getHeaderValue(headerName); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { return Flux.using(() -> span, s -> response.getBody() .doOnError(e -> tracer.end(null, e, s)) .doOnCancel(() -> tracer.end(CANCELLED_ERROR_TYPE, null, s)), s -> endNoError()); } @Override public Mono<byte[]> getBodyAsByteArray() { return endSpanWhen(response.getBodyAsByteArray()); } @Override public Mono<String> getBodyAsString() { return endSpanWhen(response.getBodyAsString()); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return endSpanWhen(response.getBodyAsString(charset)); } @Override public Mono<InputStream> getBodyAsInputStream() { return endSpanWhen(response.getBodyAsInputStream()); } @Override public void close() { response.close(); endNoError(); } private <T> Mono<T> endSpanWhen(Mono<T> publisher) { return Mono.using(() -> span, s -> publisher.doOnError(e -> tracer.end(null, e, s)) .doOnCancel(() -> tracer.end(CANCELLED_ERROR_TYPE, null, s)), s -> endNoError()); } private void endNoError() { String errorType = null; if (response == null) { errorType = OTHER_ERROR_TYPE; } else if (response.getStatusCode() >= 400) { errorType = String.valueOf(response.getStatusCode()); } tracer.end(errorType, null, span); } }
class TraceableResponse extends HttpResponse { private final HttpResponse response; private final Context span; private final Tracer tracer; private volatile int ended = 0; private static final AtomicIntegerFieldUpdater<TraceableResponse> ENDED_UPDATER = AtomicIntegerFieldUpdater.newUpdater(TraceableResponse.class, "ended"); private TraceableResponse(HttpResponse response, Tracer tracer, Context span) { super(response.getRequest()); this.response = response; this.span = span; this.tracer = tracer; } public static HttpResponse create(HttpResponse response, Tracer tracer, Context span) { if (tracer.isRecording(span)) { return new TraceableResponse(response, tracer, span); } tracer.end(null, null, span); return response; } @Override public int getStatusCode() { return response.getStatusCode(); } @Deprecated @Override public String getHeaderValue(String name) { return response.getHeaderValue(name); } @Override public String getHeaderValue(HttpHeaderName headerName) { return response.getHeaderValue(headerName); } @Override public HttpHeaders getHeaders() { return response.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { return Flux.using(() -> span, s -> response.getBody() .doOnError(e -> onError(null, e)) .doOnCancel(() -> onError(CANCELLED_ERROR_TYPE, null)), s -> endNoError()); } @Override public Mono<byte[]> getBodyAsByteArray() { return endSpanWhen(response.getBodyAsByteArray()); } @Override public Mono<String> getBodyAsString() { return endSpanWhen(response.getBodyAsString()); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return endSpanWhen(response.getBodyAsString(charset)); } @Override public Mono<InputStream> getBodyAsInputStream() { return endSpanWhen(response.getBodyAsInputStream()); } @Override public void close() { response.close(); endNoError(); } private <T> Mono<T> endSpanWhen(Mono<T> publisher) { return Mono.using(() -> span, s -> publisher.doOnError(e -> onError(null, e)).doOnCancel(() -> onError(CANCELLED_ERROR_TYPE, null)), s -> endNoError()); } private void onError(String errorType, Throwable error) { if (ENDED_UPDATER.compareAndSet(this, 0, 1)) { tracer.end(errorType, error, span); } } private void endNoError() { if (ENDED_UPDATER.compareAndSet(this, 0, 1)) { String errorType = null; if (response == null) { errorType = OTHER_ERROR_TYPE; } else if (response.getStatusCode() >= 400) { errorType = String.valueOf(response.getStatusCode()); } tracer.end(errorType, null, span); } } }