示例#1
0
        public override async Task <ResponseMessage> ReadNextAsync(CancellationToken cancellationToken = default)
        {
            CosmosDiagnosticsContext diagnostics = CosmosDiagnosticsContext.Create(this.requestOptions);

            using (diagnostics.GetOverallScope())
            {
                // This catches exception thrown by the pipeline and converts it to QueryResponse
                QueryResponseCore responseCore = await this.cosmosQueryExecutionContext.ExecuteNextAsync(cancellationToken);

                // This swaps the diagnostics in the context. This shows all the page reads between the previous ReadNextAsync and the current ReadNextAsync
                diagnostics.AddDiagnosticsInternal(this.cosmosQueryContext.GetAndResetDiagnostics());

                if (responseCore.IsSuccess)
                {
                    List <CosmosElement> decryptedCosmosElements = null;
                    if (this.clientContext.ClientOptions.Encryptor != null)
                    {
                        decryptedCosmosElements = await this.GetDecryptedElementResponseAsync(responseCore.CosmosElements, diagnostics, cancellationToken);
                    }

                    return(QueryResponse.CreateSuccess(
                               result: decryptedCosmosElements ?? responseCore.CosmosElements,
                               count: responseCore.CosmosElements.Count,
                               responseLengthBytes: responseCore.ResponseLengthBytes,
                               diagnostics: diagnostics,
                               serializationOptions: this.cosmosSerializationFormatOptions,
                               responseHeaders: new CosmosQueryResponseMessageHeaders(
                                   responseCore.ContinuationToken,
                                   responseCore.DisallowContinuationTokenMessage,
                                   this.cosmosQueryContext.ResourceTypeEnum,
                                   this.cosmosQueryContext.ContainerResourceId)
                    {
                        RequestCharge = responseCore.RequestCharge,
                        ActivityId = responseCore.ActivityId,
                        SubStatusCode = responseCore.SubStatusCode ?? Documents.SubStatusCodes.Unknown
                    }));
                }

                if (responseCore.CosmosException != null)
                {
                    return(responseCore.CosmosException.ToCosmosResponseMessage(null));
                }

                return(QueryResponse.CreateFailure(
                           statusCode: responseCore.StatusCode,
                           cosmosException: responseCore.CosmosException,
                           requestMessage: null,
                           diagnostics: diagnostics,
                           responseHeaders: new CosmosQueryResponseMessageHeaders(
                               responseCore.ContinuationToken,
                               responseCore.DisallowContinuationTokenMessage,
                               this.cosmosQueryContext.ResourceTypeEnum,
                               this.cosmosQueryContext.ContainerResourceId)
                {
                    RequestCharge = responseCore.RequestCharge,
                    ActivityId = responseCore.ActivityId,
                    SubStatusCode = responseCore.SubStatusCode ?? Documents.SubStatusCodes.Unknown,
                }));
            }
        }
示例#2
0
        public void ValidateClientSideRequestStatisticsToString()
        {
            // Verify that API using the interface get the older v2 string
            CosmosDiagnosticsContext diagnosticsContext = MockCosmosUtil.CreateDiagnosticsContext();

            diagnosticsContext.GetOverallScope().Dispose();

            CosmosClientSideRequestStatistics clientSideRequestStatistics = new CosmosClientSideRequestStatistics(diagnosticsContext);
            string noInfo = clientSideRequestStatistics.ToString();

            Assert.AreEqual("Please see CosmosDiagnostics", noInfo);

            StringBuilder stringBuilder = new StringBuilder();

            clientSideRequestStatistics.AppendToBuilder(stringBuilder);
            string noInfoStringBuilder = stringBuilder.ToString();

            Assert.AreEqual("Please see CosmosDiagnostics", noInfo);

            string id = clientSideRequestStatistics.RecordAddressResolutionStart(new Uri("https://testuri"));

            clientSideRequestStatistics.RecordAddressResolutionEnd(id);

            Documents.DocumentServiceRequest documentServiceRequest = new Documents.DocumentServiceRequest(
                operationType: Documents.OperationType.Read,
                resourceIdOrFullName: null,
                resourceType: Documents.ResourceType.Database,
                body: null,
                headers: null,
                isNameBased: false,
                authorizationTokenType: Documents.AuthorizationTokenType.PrimaryMasterKey);

            clientSideRequestStatistics.RecordRequest(documentServiceRequest);
            clientSideRequestStatistics.RecordResponse(
                documentServiceRequest,
                new Documents.StoreResult(
                    storeResponse: new Documents.StoreResponse(),
                    exception: null,
                    partitionKeyRangeId: "PkRange",
                    lsn: 42,
                    quorumAckedLsn: 4242,
                    requestCharge: 9000.42,
                    currentReplicaSetSize: 3,
                    currentWriteQuorum: 4,
                    isValid: true,
                    storePhysicalAddress: null,
                    globalCommittedLSN: 2,
                    numberOfReadRegions: 1,
                    itemLSN: 5,
                    sessionToken: null,
                    usingLocalLSN: true,
                    activityId: Guid.NewGuid().ToString()));

            string statistics = clientSideRequestStatistics.ToString();

            Assert.AreEqual("Please see CosmosDiagnostics", statistics);
        }
        /// <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.changeFeedStartFrom.Accept(ChangeFeedRangeExtractor.Singleton)));
                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,
                                           requestUriString: null,
                                           diagnosticsContext: diagnostics)));
                        }
                    }

                    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,
                                       requestUriString: null,
                                       diagnosticsContext: diagnostics)));
                    }
                }

                return(await this.ReadNextInternalAsync(diagnostics, cancellationToken));
            }
        }
示例#4
0
 internal CosmosDiagnosticsContext GetAndResetDiagnostics()
 {
     // Safely swap the current diagnostics for the new diagnostics.
     lock (this.diagnosticLock)
     {
         CosmosDiagnosticsContext current = this.diagnosticsContext;
         this.diagnosticsContext = CosmosDiagnosticsContext.Create(new RequestOptions());
         current.GetOverallScope().Dispose();
         return(current);
     }
 }
示例#5
0
        public override async Task <FeedResponse <ChangeFeedProcessorState> > ReadNextAsync(CancellationToken cancellationToken = default)
        {
            CosmosDiagnosticsContext diagnostics = CosmosDiagnosticsContext.Create(requestOptions: null);

            using (diagnostics.GetOverallScope())
            {
                if (!this.lazyLeaseDocuments.ValueInitialized)
                {
                    using (diagnostics.CreateScope("InitializeLeaseStore"))
                    {
                        await this.InitializeLeaseStoreAsync(cancellationToken);
                    }

                    using (diagnostics.CreateScope("InitializeLeaseDocuments"))
                    {
                        TryCatch <IReadOnlyList <DocumentServiceLease> > tryInitializeLeaseDocuments = await this.lazyLeaseDocuments
                                                                                                       .GetValueAsync(
                            NoOpTrace.Singleton,
                            cancellationToken)
                                                                                                       .ConfigureAwait(false);

                        if (!tryInitializeLeaseDocuments.Succeeded)
                        {
                            if (!(tryInitializeLeaseDocuments.Exception.InnerException is CosmosException cosmosException))
                            {
                                throw new InvalidOperationException("Failed to convert to CosmosException.");
                            }

                            throw cosmosException;
                        }

                        this.currentPage = 0;
                        if (this.changeFeedEstimatorRequestOptions.MaxItemCount.HasValue)
                        {
                            this.pageSize = this.changeFeedEstimatorRequestOptions.MaxItemCount.Value;
                            this.maxPage  = (int)Math.Ceiling((double)this.lazyLeaseDocuments.Result.Result.Count / this.pageSize);
                        }
                        else
                        {
                            // Get all leases in a single request
                            this.pageSize = this.lazyLeaseDocuments.Result.Result.Count;
                            this.maxPage  = 1;
                        }
                    }
                }

                return(await this.ReadNextInternalAsync(diagnostics, cancellationToken));
            }
        }
示例#6
0
        public override async Task <ResponseMessage> ReadNextAsync(CancellationToken cancellationToken = default)
        {
            CosmosDiagnosticsContext diagnostics = CosmosDiagnosticsContext.Create(this.requestOptions);

            using (diagnostics.GetOverallScope())
            {
                TryCatch <QueryPage> tryGetQueryPage;
                try
                {
                    // This catches exception thrown by the pipeline and converts it to QueryResponse
                    this.queryPipelineStage.SetCancellationToken(cancellationToken);
                    if (!await this.queryPipelineStage.MoveNextAsync())
                    {
                        this.hasMoreResults = false;
                        return(QueryResponse.CreateSuccess(
                                   result: EmptyPage,
                                   count: EmptyPage.Count,
                                   responseLengthBytes: default,