public override Task <QueryResponseCore> ExecuteNextAsync(CancellationToken cancellationToken)
        {
            QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(this.exception);

            this.returnedErrorResponse = true;
            return(Task.FromResult(queryResponse));
        }
        public override async Task <QueryResponseCore> ExecuteNextAsync(CancellationToken cancellationToken)
        {
            if (this.IsDone)
            {
                throw new InvalidOperationException(
                          $"Can not {nameof(ExecuteNextAsync)} from a {nameof(CosmosQueryExecutionContext)} where {nameof(this.IsDone)}.");
            }

            cancellationToken.ThrowIfCancellationRequested();

            QueryResponseCore queryResponseCore;

            try
            {
                queryResponseCore = await this.cosmosQueryExecutionContext.ExecuteNextAsync(cancellationToken);
            }
            catch (OperationCanceledException) when(cancellationToken.IsCancellationRequested)
            {
                // Per cancellationToken.ThrowIfCancellationRequested(); line above, this function should still throw OperationCanceledException.
                throw;
            }
            catch (Exception ex)
            {
                queryResponseCore = QueryResponseFactory.CreateFromException(ex);
            }

            if (!queryResponseCore.IsSuccess)
            {
                this.hitException = true;
            }

            return(queryResponseCore);
        }
コード例 #3
0
        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)));
        }
コード例 #4
0
        public void QueryException()
        {
            QueryException    queryException = new MalformedContinuationTokenException();
            QueryResponseCore queryResponse  = QueryResponseFactory.CreateFromException(queryException);

            Assert.AreEqual(HttpStatusCode.BadRequest, queryResponse.StatusCode);
            Assert.IsNotNull(queryResponse.ErrorMessage);
        }
コード例 #5
0
        public void DocumentClientException()
        {
            Documents.DocumentClientException documentClientException = new Documents.RequestRateTooLargeException("asdf");
            QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(documentClientException);

            Assert.AreEqual((HttpStatusCode)429, queryResponse.StatusCode);
            Assert.IsNotNull(queryResponse.ErrorMessage);
        }
コード例 #6
0
        public void CosmosException()
        {
            CosmosException cosmosException = CosmosExceptionFactory.CreateBadRequestException(
                message: "asdf");
            QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(cosmosException);

            Assert.AreEqual(HttpStatusCode.BadRequest, queryResponse.StatusCode);
            Assert.IsNotNull(queryResponse.CosmosException);
        }
コード例 #7
0
        public void ExceptionFromTryCatch()
        {
            TryCatch <object> tryCatch      = this.QueryExceptionHelper(new MalformedContinuationTokenException("TestMessage"));
            QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(tryCatch.Exception);

            Assert.AreEqual(HttpStatusCode.BadRequest, queryResponse.StatusCode);
            Assert.IsNotNull(queryResponse.CosmosException);
            Assert.IsTrue(queryResponse.CosmosException.ToString().Contains("TestMessage"));
            Assert.IsTrue(queryResponse.CosmosException.ToString().Contains(nameof(QueryExceptionHelper)), queryResponse.CosmosException.ToString());
        }
コード例 #8
0
        public void ExceptionFromTryCatch()
        {
            QueryException    queryException = new MalformedContinuationTokenException();
            TryCatch <object> tryCatch       = TryCatch <object> .FromException(queryException);

            QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(tryCatch.Exception);

            Assert.AreEqual(HttpStatusCode.BadRequest, queryResponse.StatusCode);
            Assert.IsNotNull(queryResponse.ErrorMessage);
            Assert.IsTrue(queryResponse.ErrorMessage.Contains(nameof(ExceptionFromTryCatch)));
        }
コード例 #9
0
 protected void SetupBenchmark <T>(Func <int, Document> entityFactory) where T : KeysOnlyEntity, new()
 {
     _responseContentBytes = QueryResponseFactory.CreateResponse(entityFactory, EntitiesCount);
     _describeTableBytes   = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new DescribeTableResponse(new TableDescription
     {
         TableName            = "production_" + Tables.TestTable,
         KeySchema            = new[] { new KeySchemaElement("pk", KeyType.HASH), new KeySchemaElement("sk", KeyType.RANGE) },
         AttributeDefinitions = new[] { new AttributeDefinition("pk", "S"), new AttributeDefinition("sk", "S") }
     }), new JsonSerializerOptions
     {
         Converters = { new DdbEnumJsonConverterFactory() }
     }));
 }
コード例 #10
0
        public override async Task <QueryResponseCore> ExecuteNextAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            TryCatch <CosmosQueryExecutionContext> tryCreateCosmosQueryExecutionContext = await this.lazyTryCreateCosmosQueryExecutionContext.GetValueAsync(cancellationToken);

            if (!tryCreateCosmosQueryExecutionContext.Succeeded)
            {
                return(QueryResponseFactory.CreateFromException(tryCreateCosmosQueryExecutionContext.Exception));
            }

            CosmosQueryExecutionContext cosmosQueryExecutionContext = tryCreateCosmosQueryExecutionContext.Result;
            QueryResponseCore           queryResponseCore           = await cosmosQueryExecutionContext.ExecuteNextAsync(cancellationToken);

            return(queryResponseCore);
        }
コード例 #11
0
        public void RandomException()
        {
            QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(new Exception());

            Assert.AreEqual(HttpStatusCode.InternalServerError, queryResponse.StatusCode);
        }
コード例 #12
0
        public async Task TestCosmosOrderByQueryExecutionContextWithFailurePageAsync(bool createInitialContinuationToken)
        {
            int maxPageSize = 5;

            List <MockPartitionResponse[]> mockResponsesScenario = MockQueryFactory.GetFailureScenarios();

            Mock <CosmosQueryClient> mockQueryClient = new Mock <CosmosQueryClient>();

            foreach (MockPartitionResponse[] mockResponse in mockResponsesScenario)
            {
                string initialContinuationToken = null;
                string fullContinuationToken    = null;
                if (createInitialContinuationToken)
                {
                    ToDoItem itemToRepresentPreviousQuery = ToDoItem.CreateItems(
                        1,
                        "itemToRepresentPreviousQuery",
                        MockQueryFactory.DefaultCollectionRid).First();

                    initialContinuationToken = $" - RID:{itemToRepresentPreviousQuery._rid} ==#RT:1#TRC:1";
                    CompositeContinuationToken compositeContinuation = new CompositeContinuationToken()
                    {
                        Range = new Documents.Routing.Range <string>(
                            min: MockQueryFactory.DefaultPartitionKeyRange.MinInclusive,
                            max: MockQueryFactory.DefaultPartitionKeyRange.MaxExclusive,
                            isMaxInclusive: false,
                            isMinInclusive: true),
                        Token = initialContinuationToken
                    };

                    List <OrderByItem> orderByItems = new List <OrderByItem>()
                    {
                        new OrderByItem(CosmosObject.CreateFromBuffer(Encoding.UTF8.GetBytes("{\"item\":\"2c4ce711-13c3-4c93-817c-49287b71b6c3\"}")))
                    };

                    OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken(
                        compositeContinuationToken: compositeContinuation,
                        orderByItems: orderByItems,
                        rid: itemToRepresentPreviousQuery._rid,
                        skipCount: 0,
                        filter: null);

                    fullContinuationToken = CosmosArray.Create(
                        new List <CosmosElement>()
                    {
                        OrderByContinuationToken.ToCosmosElement(orderByContinuationToken)
                    }).ToString();
                }

                IList <ToDoItem> allItems = MockQueryFactory.GenerateAndMockResponse(
                    mockQueryClient,
                    isOrderByQuery: true,
                    sqlQuerySpec: MockQueryFactory.DefaultQuerySpec,
                    containerRid: MockQueryFactory.DefaultCollectionRid,
                    initContinuationToken: initialContinuationToken,
                    maxPageSize: maxPageSize,
                    mockResponseForSinglePartition: mockResponse,
                    cancellationTokenForMocks: this.cancellationToken);

                // Order by drains the partitions until it finds an item
                // If there are no items then it's not possible to have a continuation token
                if (allItems.Count == 0 && createInitialContinuationToken)
                {
                    continue;
                }

                CosmosQueryContext context = MockQueryFactory.CreateContext(
                    mockQueryClient.Object);

                QueryInfo queryInfo = new QueryInfo()
                {
                    OrderBy            = new SortOrder[] { SortOrder.Ascending },
                    OrderByExpressions = new string[] { "id" }
                };

                CosmosCrossPartitionQueryExecutionContext.CrossPartitionInitParams initParams = new CosmosCrossPartitionQueryExecutionContext.CrossPartitionInitParams(
                    sqlQuerySpec: MockQueryFactory.DefaultQuerySpec,
                    collectionRid: MockQueryFactory.DefaultCollectionRid,
                    partitionedQueryExecutionInfo: new PartitionedQueryExecutionInfo()
                {
                    QueryInfo = queryInfo
                },
                    partitionKeyRanges: new List <PartitionKeyRange>()
                {
                    MockQueryFactory.DefaultPartitionKeyRange
                },
                    initialPageSize: maxPageSize,
                    maxConcurrency: null,
                    maxItemCount: maxPageSize,
                    maxBufferedItemCount: null,
                    returnResultsInDeterministicOrder: true,
                    testSettings: new TestInjections(simulate429s: false, simulateEmptyPages: false));

                TryCatch <IDocumentQueryExecutionComponent> tryCreate = await CosmosOrderByItemQueryExecutionContext.TryCreateAsync(
                    context,
                    initParams,
                    fullContinuationToken != null?CosmosElement.Parse(fullContinuationToken) : null,
                    this.cancellationToken);

                if (tryCreate.Succeeded)
                {
                    IDocumentQueryExecutionComponent executionContext = tryCreate.Result;

                    Assert.IsTrue(!executionContext.IsDone);

                    // Read all the pages from both splits
                    List <ToDoItem>   itemsRead = new List <ToDoItem>();
                    QueryResponseCore?failure   = null;
                    while (!executionContext.IsDone)
                    {
                        QueryResponseCore queryResponse = await executionContext.DrainAsync(
                            maxPageSize,
                            this.cancellationToken);

                        if (queryResponse.IsSuccess)
                        {
                            string responseContinuationToken = queryResponse.ContinuationToken;
                            foreach (CosmosElement element in queryResponse.CosmosElements)
                            {
                                string   jsonValue = element.ToString();
                                ToDoItem item      = JsonConvert.DeserializeObject <ToDoItem>(jsonValue);
                                itemsRead.Add(item);
                            }
                        }
                        else
                        {
                            Assert.IsNull(failure, "There should only be one error");
                            failure = queryResponse;
                        }
                    }

                    Assert.IsNotNull(failure);
                    Assert.AreEqual((HttpStatusCode)429, failure.Value.StatusCode);
                    Assert.IsNotNull(failure.Value.CosmosException.ToString());

                    Assert.AreEqual(0 /*We don't get any items, since we don't buffer the failure anymore*/, itemsRead.Count);

                    //CollectionAssert.AreEqual(allItems.ToList(), itemsRead, new ToDoItemComparer());
                }
                else
                {
                    QueryResponseCore queryResponseCore = QueryResponseFactory.CreateFromException(tryCreate.Exception);
                    Assert.AreEqual((HttpStatusCode)429, queryResponseCore.StatusCode);
                }
            }
        }
コード例 #13
0
 private void SetupBenchmark <T>(Func <int, Document> entityFactory) where T : KeysOnlyEntity, new()
 {
     _responseContentBytes = QueryResponseFactory.CreateResponse(entityFactory, EntitiesCount);
     _describeTableBytes   = DescribeTableResponseFactory.CreateResponse();
 }
コード例 #14
0
 private byte[] GenerateQueryResponseJson(int itemsCount) => QueryResponseFactory.CreateResponse(CreateEntity, itemsCount);