public void VerifyNegativeCosmosQueryResponseStream() { string contianerRid = "mockContainerRid"; string errorMessage = "TestErrorMessage"; string activityId = "TestActivityId"; double requestCharge = 42.42; CosmosDiagnosticsContext diagnostics = new CosmosDiagnosticsContextCore(); CosmosException cosmosException = CosmosExceptionFactory.CreateBadRequestException(errorMessage, diagnosticsContext: diagnostics); diagnostics.GetOverallScope().Dispose(); QueryResponse queryResponse = QueryResponse.CreateFailure( statusCode: HttpStatusCode.NotFound, cosmosException: cosmosException, requestMessage: null, responseHeaders: new CosmosQueryResponseMessageHeaders( null, null, ResourceType.Document, contianerRid) { RequestCharge = requestCharge, ActivityId = activityId }, diagnostics: diagnostics); Assert.AreEqual(HttpStatusCode.NotFound, queryResponse.StatusCode); Assert.AreEqual(cosmosException.Message, queryResponse.ErrorMessage); Assert.AreEqual(requestCharge, queryResponse.Headers.RequestCharge); Assert.AreEqual(activityId, queryResponse.Headers.ActivityId); Assert.AreEqual(diagnostics, queryResponse.DiagnosticsContext); Assert.IsNull(queryResponse.Content); }
internal async Task <(byte[], EncryptionKeyWrapMetadata, InMemoryRawDek)> WrapAsync( byte[] key, CosmosEncryptionAlgorithm encryptionAlgorithmId, EncryptionKeyWrapMetadata metadata, CosmosDiagnosticsContext diagnosticsContext, CancellationToken cancellationToken) { EncryptionKeyWrapProvider encryptionKeyWrapProvider = this.ClientContext.ClientOptions.EncryptionKeyWrapProvider; if (encryptionKeyWrapProvider == null) { throw new ArgumentException(ClientResources.EncryptionKeyWrapProviderNotConfigured); } EncryptionKeyWrapResult keyWrapResponse; using (diagnosticsContext.CreateScope("WrapDataEncryptionKey")) { keyWrapResponse = await encryptionKeyWrapProvider.WrapKeyAsync(key, metadata, cancellationToken); } // Verify DataEncryptionKeyProperties tempDekProperties = new DataEncryptionKeyProperties(this.Id, encryptionAlgorithmId, keyWrapResponse.WrappedDataEncryptionKey, keyWrapResponse.EncryptionKeyWrapMetadata); InMemoryRawDek roundTripResponse = await this.UnwrapAsync(tempDekProperties, diagnosticsContext, cancellationToken); if (!roundTripResponse.RawDek.SequenceEqual(key)) { throw CosmosExceptionFactory.CreateBadRequestException(ClientResources.KeyWrappingDidNotRoundtrip, diagnosticsContext: diagnosticsContext); } return(keyWrapResponse.WrappedDataEncryptionKey, keyWrapResponse.EncryptionKeyWrapMetadata, roundTripResponse); }
public void ExceptionFromTryCatchWithCosmosException() { CosmosException cosmosException; try { throw CosmosExceptionFactory.CreateBadRequestException("InternalServerTestMessage", new Headers()); } catch (CosmosException ce) { cosmosException = ce; } TryCatch <object> tryCatch = this.QueryExceptionHelper(cosmosException); QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(tryCatch.Exception); Assert.AreEqual(HttpStatusCode.BadRequest, queryResponse.StatusCode); Assert.IsNotNull(queryResponse.CosmosException); // Should preserve the original stack trace. string exceptionMessage = queryResponse.CosmosException.ToString(); Assert.IsTrue(exceptionMessage.Contains("InternalServerTestMessage")); Assert.IsFalse(exceptionMessage.Contains(nameof(QueryExceptionHelper))); }
public void EnsureCorrectStatusCode() { string testMessage = "Test" + Guid.NewGuid().ToString(); string activityId = Guid.NewGuid().ToString(); int substatuscode = 9000; string substatus = substatuscode.ToString(); double requestCharge = 42; double retryAfter = 9000; string retryAfterLiteral = retryAfter.ToString(); List <(HttpStatusCode statusCode, CosmosException exception)> exceptionsToStatusCodes = new List <(HttpStatusCode, CosmosException)>() { (HttpStatusCode.NotFound, CosmosExceptionFactory.CreateNotFoundException(testMessage, new Headers() { SubStatusCodeLiteral = substatus, ActivityId = activityId, RequestCharge = requestCharge, RetryAfterLiteral = retryAfterLiteral })), (HttpStatusCode.InternalServerError, CosmosExceptionFactory.CreateInternalServerErrorException(testMessage, new Headers() { SubStatusCodeLiteral = substatus, ActivityId = activityId, RequestCharge = requestCharge, RetryAfterLiteral = retryAfterLiteral })), (HttpStatusCode.BadRequest, CosmosExceptionFactory.CreateBadRequestException(testMessage, new Headers() { SubStatusCodeLiteral = substatus, ActivityId = activityId, RequestCharge = requestCharge, RetryAfterLiteral = retryAfterLiteral })), (HttpStatusCode.RequestTimeout, CosmosExceptionFactory.CreateRequestTimeoutException(testMessage, new Headers() { SubStatusCodeLiteral = substatus, ActivityId = activityId, RequestCharge = requestCharge, RetryAfterLiteral = retryAfterLiteral })), ((HttpStatusCode)429, CosmosExceptionFactory.CreateThrottledException(testMessage, new Headers() { SubStatusCodeLiteral = substatus, ActivityId = activityId, RequestCharge = requestCharge, RetryAfterLiteral = retryAfterLiteral })), }; foreach ((HttpStatusCode statusCode, CosmosException exception) in exceptionsToStatusCodes) { this.ValidateExceptionInfo( exception, statusCode, substatus, testMessage, activityId, requestCharge, retryAfter); } CosmosException cosmosException = CosmosExceptionFactory.CreateNotFoundException(testMessage, new Headers() { SubStatusCodeLiteral = ((int)SubStatusCodes.ReadSessionNotAvailable).ToString(), ActivityId = activityId, RequestCharge = requestCharge, RetryAfterLiteral = retryAfterLiteral }); this.ValidateExceptionInfo( cosmosException, HttpStatusCode.NotFound, ((int)SubStatusCodes.ReadSessionNotAvailable).ToString(), testMessage, activityId, requestCharge, retryAfter); }
public static async Task <PartitionedQueryExecutionInfo> GetQueryPlanWithServiceInteropAsync( CosmosQueryClient queryClient, SqlQuerySpec sqlQuerySpec, Documents.ResourceType resourceType, PartitionKeyDefinition partitionKeyDefinition, bool hasLogicalPartitionKey, bool useSystemPrefix, ITrace trace, CancellationToken cancellationToken = default) { if (queryClient == null) { throw new ArgumentNullException(nameof(queryClient)); } if (sqlQuerySpec == null) { throw new ArgumentNullException(nameof(sqlQuerySpec)); } if (partitionKeyDefinition == null) { throw new ArgumentNullException(nameof(partitionKeyDefinition)); } cancellationToken.ThrowIfCancellationRequested(); using (ITrace serviceInteropTrace = trace.StartChild("Service Interop Query Plan", TraceComponent.Query, TraceLevel.Info)) { QueryPlanHandler queryPlanHandler = new QueryPlanHandler(queryClient); TryCatch <PartitionedQueryExecutionInfo> tryGetQueryPlan = await queryPlanHandler.TryGetQueryPlanAsync( sqlQuerySpec, resourceType, partitionKeyDefinition, QueryPlanRetriever.SupportedQueryFeatures, hasLogicalPartitionKey, useSystemPrefix, cancellationToken); if (!tryGetQueryPlan.Succeeded) { Exception originalException = ExceptionWithStackTraceException.UnWrapMonadExcepion(tryGetQueryPlan.Exception, serviceInteropTrace); if (originalException is CosmosException) { throw originalException; } throw CosmosExceptionFactory.CreateBadRequestException( message: originalException.Message, headers: new Headers(), stackTrace: tryGetQueryPlan.Exception.StackTrace, innerException: originalException, trace: trace); } return(tryGetQueryPlan.Result); } }
public override CosmosException Visit(MalformedContinuationTokenException malformedContinuationTokenException) { return(CosmosExceptionFactory.CreateBadRequestException( message: malformedContinuationTokenException.Message, headers: new Headers(), stackTrace: malformedContinuationTokenException.StackTrace, innerException: malformedContinuationTokenException)); }
public override CosmosException Visit(ExpectedQueryPartitionProviderException expectedQueryPartitionProviderException) { return(CosmosExceptionFactory.CreateBadRequestException( message: expectedQueryPartitionProviderException.Message, headers: new Headers(), stackTrace: expectedQueryPartitionProviderException.StackTrace, innerException: expectedQueryPartitionProviderException)); }
public void CosmosException() { CosmosException cosmosException = CosmosExceptionFactory.CreateBadRequestException( message: "asdf"); QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(cosmosException); Assert.AreEqual(HttpStatusCode.BadRequest, queryResponse.StatusCode); Assert.IsNotNull(queryResponse.CosmosException); }
/// <summary> /// Get the next set of results from the cosmos service /// </summary> /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param> /// <returns>A query response from cosmos service</returns> public override async Task <ResponseMessage> ReadNextAsync(CancellationToken cancellationToken = default) { CosmosDiagnosticsContext diagnostics = CosmosDiagnosticsContext.Create(this.changeFeedOptions); using (diagnostics.GetOverallScope()) { diagnostics.AddDiagnosticsInternal(new FeedRangeStatistics(this.changeFeedOptions.FeedRange)); if (!this.lazyContainerRid.ValueInitialized) { using (diagnostics.CreateScope("InitializeContainerResourceId")) { TryCatch <string> tryInitializeContainerRId = await this.lazyContainerRid.GetValueAsync(cancellationToken); if (!tryInitializeContainerRId.Succeeded) { if (!(tryInitializeContainerRId.Exception.InnerException is CosmosException cosmosException)) { throw new InvalidOperationException("Failed to convert to CosmosException."); } return(cosmosException.ToCosmosResponseMessage( new RequestMessage( method: null, requestUri: null, diagnosticsContext: diagnostics))); } } if (this.FeedRangeContinuation == null) { using (diagnostics.CreateScope("InitializeContinuation")) { await this.InitializeFeedContinuationAsync(cancellationToken); } } TryCatch validateContainer = this.FeedRangeContinuation.ValidateContainer(this.lazyContainerRid.Result.Result); if (!validateContainer.Succeeded) { return(CosmosExceptionFactory .CreateBadRequestException( message: validateContainer.Exception.InnerException.Message, innerException: validateContainer.Exception.InnerException, diagnosticsContext: diagnostics) .ToCosmosResponseMessage( new RequestMessage( method: null, requestUri: null, diagnosticsContext: diagnostics))); } } return(await this.ReadNextInternalAsync(diagnostics, cancellationToken)); } }
internal override CosmosException Visit( MalformedChangeFeedContinuationTokenException malformedChangeFeedContinuationTokenException, ITrace trace) { return(CosmosExceptionFactory.CreateBadRequestException( message: malformedChangeFeedContinuationTokenException.Message, headers: new Headers(), stackTrace: malformedChangeFeedContinuationTokenException.StackTrace, innerException: malformedChangeFeedContinuationTokenException, trace: trace)); }
public static async Task <PartitionedQueryExecutionInfo> GetQueryPlanWithServiceInteropAsync( CosmosQueryClient queryClient, SqlQuerySpec sqlQuerySpec, PartitionKeyDefinition partitionKeyDefinition, bool hasLogicalPartitionKey, ITrace trace, CancellationToken cancellationToken = default) { if (queryClient == null) { throw new ArgumentNullException(nameof(queryClient)); } if (sqlQuerySpec == null) { throw new ArgumentNullException(nameof(sqlQuerySpec)); } if (partitionKeyDefinition == null) { throw new ArgumentNullException(nameof(partitionKeyDefinition)); } cancellationToken.ThrowIfCancellationRequested(); using (ITrace serviceInteropTrace = trace.StartChild("Service Interop Query Plan", TraceComponent.Query, TraceLevel.Info)) { QueryPlanHandler queryPlanHandler = new QueryPlanHandler(queryClient); TryCatch <PartitionedQueryExecutionInfo> tryGetQueryPlan = await queryPlanHandler.TryGetQueryPlanAsync( sqlQuerySpec, partitionKeyDefinition, QueryPlanRetriever.SupportedQueryFeatures, hasLogicalPartitionKey, cancellationToken); if (!tryGetQueryPlan.Succeeded) { if (tryGetQueryPlan.Exception is CosmosException) { throw tryGetQueryPlan.Exception; } throw CosmosExceptionFactory.CreateBadRequestException( message: tryGetQueryPlan.Exception.ToString(), stackTrace: tryGetQueryPlan.Exception.StackTrace); } return(tryGetQueryPlan.Result); } }
public override CosmosException Visit(MalformedContinuationTokenException malformedContinuationTokenException, ITrace trace) { Headers headers = new Headers() { SubStatusCode = Documents.SubStatusCodes.MalformedContinuationToken }; return(CosmosExceptionFactory.CreateBadRequestException( message: malformedContinuationTokenException.Message, headers: headers, stackTrace: malformedContinuationTokenException.StackTrace, innerException: malformedContinuationTokenException, trace: trace)); }
public void EnsureCorrectStatusCode() { string testMessage = "Test" + Guid.NewGuid().ToString(); List <(HttpStatusCode statusCode, CosmosException exception)> exceptionsToStatusCodes = new List <(HttpStatusCode, CosmosException)>() { (HttpStatusCode.NotFound, CosmosExceptionFactory.CreateNotFoundException(testMessage, activityId: Guid.NewGuid().ToString())), (HttpStatusCode.InternalServerError, CosmosExceptionFactory.CreateInternalServerErrorException(testMessage, activityId: Guid.NewGuid().ToString())), (HttpStatusCode.BadRequest, CosmosExceptionFactory.CreateBadRequestException(testMessage, activityId: Guid.NewGuid().ToString())), (HttpStatusCode.RequestTimeout, CosmosExceptionFactory.CreateRequestTimeoutException(testMessage, activityId: Guid.NewGuid().ToString())), ((HttpStatusCode)429, CosmosExceptionFactory.CreateThrottledException(testMessage, activityId: Guid.NewGuid().ToString())), }; foreach ((HttpStatusCode statusCode, CosmosException exception)item in exceptionsToStatusCodes) { this.ValidateExceptionInfo(item.exception, item.statusCode, testMessage); } }
/// <summary> /// Get the next set of results from the cosmos service /// </summary> /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param> /// <returns>A query response from cosmos service</returns> public override async Task <ResponseMessage> ReadNextAsync(CancellationToken cancellationToken = default) { CosmosDiagnosticsContext diagnostics = CosmosDiagnosticsContext.Create(this.queryRequestOptions); using (diagnostics.GetOverallScope()) { if (!this.lazyContainerRid.ValueInitialized) { using (diagnostics.CreateScope("InitializeContainerResourceId")) { TryCatch <string> tryInitializeContainerRId = await this.lazyContainerRid.GetValueAsync(cancellationToken); if (!tryInitializeContainerRId.Succeeded) { CosmosException cosmosException = tryInitializeContainerRId.Exception.InnerException as CosmosException; return(cosmosException.ToCosmosResponseMessage(new RequestMessage(method: null, requestUriString: null, diagnosticsContext: diagnostics))); } } using (diagnostics.CreateScope("InitializeContinuation")) { if (this.FeedRangeContinuation != null) { TryCatch validateContainer = this.FeedRangeContinuation.ValidateContainer(this.lazyContainerRid.Result.Result); if (!validateContainer.Succeeded) { return(CosmosExceptionFactory.CreateBadRequestException( message: validateContainer.Exception.InnerException.Message, innerException: validateContainer.Exception.InnerException, diagnosticsContext: diagnostics).ToCosmosResponseMessage(new RequestMessage(method: null, requestUriString: null, diagnosticsContext: diagnostics))); } } else { await this.InitializeFeedContinuationAsync(cancellationToken); } } } return(await this.ReadNextInternalAsync(diagnostics, cancellationToken)); } }
public void FeedRangeResponse_ResponseIsAccessible() { ResponseMessage original = new ResponseMessage( System.Net.HttpStatusCode.OK, new RequestMessage(), new Headers(), CosmosExceptionFactory.CreateBadRequestException("test"), CosmosDiagnosticsContext.Create(new RequestOptions())); original.Content = Mock.Of <MemoryStream>(); Mock <FeedRangeContinuation> feedContinuation = new Mock <FeedRangeContinuation>(); ResponseMessage feedRangeResponse = FeedRangeResponse.CreateSuccess(original, feedContinuation.Object); Assert.AreEqual(original.Content, feedRangeResponse.Content); Assert.AreEqual(original.StatusCode, feedRangeResponse.StatusCode); Assert.AreEqual(original.RequestMessage, feedRangeResponse.RequestMessage); Assert.AreEqual(original.Headers, feedRangeResponse.Headers); Assert.AreEqual(original.CosmosException, feedRangeResponse.CosmosException); Assert.AreEqual(original.DiagnosticsContext, feedRangeResponse.DiagnosticsContext); }
public void FeedRangeResponse_ResponseIsAccessible() { Headers headers = new Headers(); ResponseMessage original = new ResponseMessage( System.Net.HttpStatusCode.OK, new RequestMessage(), headers, CosmosExceptionFactory.CreateBadRequestException("test", headers), NoOpTrace.Singleton) { Content = Mock.Of <MemoryStream>() }; Mock <FeedRangeContinuation> feedContinuation = new Mock <FeedRangeContinuation>(); ResponseMessage feedRangeResponse = FeedRangeResponse.CreateSuccess(original, feedContinuation.Object); Assert.AreEqual(original.Content, feedRangeResponse.Content); Assert.AreEqual(original.StatusCode, feedRangeResponse.StatusCode); Assert.AreEqual(original.RequestMessage, feedRangeResponse.RequestMessage); Assert.AreEqual(original.Headers, feedRangeResponse.Headers); Assert.AreEqual(original.CosmosException, feedRangeResponse.CosmosException); }
public void ValidateErrorHandling() { Error error = new Error() { Code = System.Net.HttpStatusCode.BadRequest.ToString(), Message = "Unsupported Query", AdditionalErrorInfo = "Additional error info message", }; CosmosDiagnosticsContext diagnostics = new CosmosDiagnosticsContextCore(); CosmosException cosmosException = CosmosExceptionFactory.CreateBadRequestException( error.ToString(), error: error, diagnosticsContext: diagnostics); ResponseMessage responseMessage = QueryResponse.CreateFailure( statusCode: System.Net.HttpStatusCode.BadRequest, cosmosException: cosmosException, requestMessage: null, diagnostics: diagnostics, responseHeaders: null); Assert.AreEqual(error, responseMessage.CosmosException.Error); Assert.IsTrue(responseMessage.ErrorMessage.Contains(error.Message)); Assert.IsTrue(responseMessage.ErrorMessage.Contains(error.AdditionalErrorInfo)); try { responseMessage.EnsureSuccessStatusCode(); Assert.Fail("Should throw exception"); } catch (CosmosException ce) when(ce.StatusCode == HttpStatusCode.BadRequest) { Assert.IsTrue(ce.Message.Contains(error.Message)); Assert.IsTrue(ce.ToString().Contains(error.Message)); Assert.IsTrue(ce.ToString().Contains(error.AdditionalErrorInfo)); } }
public override CosmosException Visit(ExpectedQueryPartitionProviderException expectedQueryPartitionProviderException) => CosmosExceptionFactory.CreateBadRequestException( message: expectedQueryPartitionProviderException.Message, stackTrace: expectedQueryPartitionProviderException.StackTrace, innerException: expectedQueryPartitionProviderException);
public override CosmosException Visit(MalformedContinuationTokenException malformedContinuationTokenException) => CosmosExceptionFactory.CreateBadRequestException( message: malformedContinuationTokenException.Message, stackTrace: malformedContinuationTokenException.StackTrace, innerException: malformedContinuationTokenException);