Esempio n. 1
0
        public void ValidateDiagnosticsAppendContext()
        {
            CosmosDiagnosticsContext cosmosDiagnostics = new CosmosDiagnosticsContext();

            // Test all the different operations on diagnostics context
            cosmosDiagnostics.Summary.AddSdkRetry(TimeSpan.FromSeconds(42));
            using (cosmosDiagnostics.CreateScope("ValidateScope"))
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
            }

            cosmosDiagnostics.Summary.SetSdkUserAgent("MyCustomUserAgentString");

            CosmosDiagnosticsContext cosmosDiagnostics2 = new CosmosDiagnosticsContext();

            using (cosmosDiagnostics.CreateScope("CosmosDiagnostics2Scope"))
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(100));
            }

            cosmosDiagnostics2.Append(cosmosDiagnostics);

            string diagnostics = cosmosDiagnostics2.ToString();

            Assert.IsTrue(diagnostics.Contains("MyCustomUserAgentString"));
            Assert.IsTrue(diagnostics.Contains("ValidateScope"));
            Assert.IsTrue(diagnostics.Contains("CosmosDiagnostics2Scope"));
        }
        /// <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));
            }
        }
Esempio n. 3
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));
            }
        }
Esempio n. 4
0
        private async Task <List <CosmosElement> > GetDecryptedElementResponseAsync(
            IReadOnlyList <CosmosElement> encryptedCosmosElements,
            CosmosDiagnosticsContext diagnosticsContext,
            CancellationToken cancellationToken)
        {
            List <CosmosElement> decryptedCosmosElements = new List <CosmosElement>();

            using (diagnosticsContext.CreateScope("Decrypt"))
            {
                foreach (CosmosElement document in encryptedCosmosElements)
                {
                    if (!(document is CosmosObject documentObject))
                    {
                        decryptedCosmosElements.Add(document);
                        continue;
                    }

                    CosmosObject decryptedDocument = await this.clientContext.EncryptionProcessor.DecryptAsync(
                        documentObject,
                        this.clientContext.ClientOptions.Encryptor,
                        diagnosticsContext,
                        cancellationToken);

                    decryptedCosmosElements.Add(decryptedDocument);
                }
            }

            return(decryptedCosmosElements);
        }
        public override async Task <ResponseMessage> ReadNextAsync(CancellationToken cancellationToken = default)
        {
            CosmosDiagnosticsContext diagnostics = new CosmosDiagnosticsContext();

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

                CosmosQueryContext cosmosQueryContext = this.cosmosQueryContext;

                foreach (QueryPageDiagnostics queryPage in responseCore.Diagnostics)
                {
                    diagnostics.Summary.Append(queryPage.DiagnosticsContext.Summary);
                    diagnostics.AddDiagnosticsInternal(queryPage);
                }

                QueryResponse queryResponse;
                if (responseCore.IsSuccess)
                {
                    queryResponse = QueryResponse.CreateSuccess(
                        result: responseCore.CosmosElements,
                        count: responseCore.CosmosElements.Count,
                        responseLengthBytes: responseCore.ResponseLengthBytes,
                        diagnostics: diagnostics,
                        serializationOptions: this.cosmosSerializationFormatOptions,
                        responseHeaders: new CosmosQueryResponseMessageHeaders(
                            responseCore.ContinuationToken,
                            responseCore.DisallowContinuationTokenMessage,
                            cosmosQueryContext.ResourceTypeEnum,
                            cosmosQueryContext.ContainerResourceId)
                    {
                        RequestCharge = responseCore.RequestCharge,
                        ActivityId    = responseCore.ActivityId,
                        SubStatusCode = responseCore.SubStatusCode ?? Documents.SubStatusCodes.Unknown
                    });
                }
                else
                {
                    queryResponse = QueryResponse.CreateFailure(
                        statusCode: responseCore.StatusCode,
                        error: null,
                        errorMessage: responseCore.ErrorMessage,
                        requestMessage: null,
                        diagnostics: diagnostics,
                        responseHeaders: new CosmosQueryResponseMessageHeaders(
                            responseCore.ContinuationToken,
                            responseCore.DisallowContinuationTokenMessage,
                            cosmosQueryContext.ResourceTypeEnum,
                            cosmosQueryContext.ContainerResourceId)
                    {
                        RequestCharge = responseCore.RequestCharge,
                        ActivityId    = responseCore.ActivityId,
                        SubStatusCode = responseCore.SubStatusCode ?? Documents.SubStatusCodes.Unknown
                    });
                }

                return(queryResponse);
            }
        }
Esempio n. 6
0
        public void TestUpdatesWhileVisiting()
        {
            CosmosDiagnosticsContext cosmosDiagnostics = MockCosmosUtil.CreateDiagnosticsContext();

            cosmosDiagnostics.CreateScope("FirstScope");

            bool isFirst = true;

            foreach (CosmosDiagnosticsInternal diagnostic in cosmosDiagnostics)
            {
                if (isFirst)
                {
                    cosmosDiagnostics.CreateScope("SecondScope");
                    isFirst = false;
                }

                diagnostic.ToString();
            }
        }
Esempio n. 7
0
        public void ValidateDiagnosticsContext()
        {
            CosmosDiagnosticsContext cosmosDiagnostics = new CosmosDiagnosticsContext();
            string diagnostics = cosmosDiagnostics.ToString();

            //Test the default user agent string
            JObject jObject = JObject.Parse(diagnostics);
            JToken  summary = jObject["Summary"];

            Assert.IsTrue(summary["UserAgent"].ToString().Contains("cosmos-netstandard-sdk"), "Diagnostics should have user agent string");
            Assert.AreEqual("[]", jObject["Context"].ToString());

            // Test all the different operations on diagnostics context
            cosmosDiagnostics.Summary.AddSdkRetry(TimeSpan.FromSeconds(42));
            using (cosmosDiagnostics.CreateOverallScope("OverallScope"))
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                using (cosmosDiagnostics.CreateScope("ValidateScope"))
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }

            cosmosDiagnostics.Summary.SetSdkUserAgent("MyCustomUserAgentString");

            string result = cosmosDiagnostics.ToString();

            string regex = @"\{""Summary"":\{""StartUtc"":"".+Z"",""ElapsedTime"":""00:00:.+"",""UserAgent"":""MyCustomUserAgentString"",""RetryCount"":1,""RetryBackOffTime"":""00:00:42""\},""Context"":\[\{""Id"":""OverallScope"",""ElapsedTime"":""00:00:.+""\},\{""Id"":""ValidateScope"",""ElapsedTime"":""00:00:.+""\}\]\}";

            Assert.IsTrue(Regex.IsMatch(result, regex), result);

            JToken   jToken = JToken.Parse(result);
            TimeSpan total  = jToken["Summary"]["ElapsedTime"].ToObject <TimeSpan>();

            Assert.IsTrue(total > TimeSpan.FromSeconds(2));
            TimeSpan overalScope = jToken["Context"][0]["ElapsedTime"].ToObject <TimeSpan>();

            Assert.IsTrue(total == overalScope);
            TimeSpan innerScope = jToken["Context"][1]["ElapsedTime"].ToObject <TimeSpan>();

            Assert.IsTrue(innerScope > TimeSpan.FromSeconds(1));
        }
Esempio n. 8
0
        public void ValidateDiagnosticsContext()
        {
            CosmosDiagnosticsContext cosmosDiagnostics = CosmosDiagnosticsContext.Create();
            string diagnostics = cosmosDiagnostics.ToString();

            //Test the default user agent string
            JObject jObject = JObject.Parse(diagnostics);
            JToken  summary = jObject["Summary"];

            Assert.IsTrue(summary["UserAgent"].ToString().Contains("cosmos-netstandard-sdk"), "Diagnostics should have user agent string");
            Assert.AreEqual("[]", jObject["Context"].ToString());

            // Test all the different operations on diagnostics context
            using (cosmosDiagnostics.CreateOverallScope("OverallScope"))
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                using (cosmosDiagnostics.CreateScope("ValidateScope"))
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    cosmosDiagnostics.AddDiagnosticsInternal(new PointOperationStatistics(
                                                                 new Guid("692ab2f2-41ba-486b-aad7-8c7c6c52379f").ToString(),
                                                                 (HttpStatusCode)429,
                                                                 Documents.SubStatusCodes.Unknown,
                                                                 42,
                                                                 null,
                                                                 HttpMethod.Get,
                                                                 new Uri("http://MockUri.com"),
                                                                 null,
                                                                 null,
                                                                 null));
                }

                using (cosmosDiagnostics.CreateScope("SuccessScope"))
                {
                    cosmosDiagnostics.AddDiagnosticsInternal(new PointOperationStatistics(
                                                                 new Guid("de09baab-71a4-4897-a163-470711c93ed3").ToString(),
                                                                 HttpStatusCode.OK,
                                                                 Documents.SubStatusCodes.Unknown,
                                                                 42,
                                                                 null,
                                                                 HttpMethod.Get,
                                                                 new Uri("http://MockUri.com"),
                                                                 null,
                                                                 null,
                                                                 null));
                }
            }

            cosmosDiagnostics.SetSdkUserAgent("MyCustomUserAgentString");

            string result = cosmosDiagnostics.ToString();

            string regex = @"\{""Summary"":\{""StartUtc"":"".+Z"",""ElapsedTime"":""00:00:.+"",""UserAgent"":""MyCustomUserAgentString"",""TotalRequestCount"":2,""FailedRequestCount"":1\},""Context"":\[\{""Id"":""OverallScope"",""ElapsedTime"":""00:00:0.+""\},\{""Id"":""ValidateScope"",""ElapsedTime"":""00:00:0.+""\},\{""Id"":""PointOperationStatistics"",""ActivityId"":""692ab2f2-41ba-486b-aad7-8c7c6c52379f"",""StatusCode"":429,""SubStatusCode"":0,""RequestCharge"":42.0,""RequestUri"":""http://MockUri.com"",""RequestSessionToken"":null,""ResponseSessionToken"":null\},\{""Id"":""SuccessScope"",""ElapsedTime"":""00:00:.+""\},\{""Id"":""PointOperationStatistics"",""ActivityId"":""de09baab-71a4-4897-a163-470711c93ed3"",""StatusCode"":200,""SubStatusCode"":0,""RequestCharge"":42.0,""RequestUri"":""http://MockUri.com"",""RequestSessionToken"":null,""ResponseSessionToken"":null\}\]\}";

            Assert.IsTrue(Regex.IsMatch(result, regex), result);

            JToken   jToken = JToken.Parse(result);
            TimeSpan total  = jToken["Summary"]["ElapsedTime"].ToObject <TimeSpan>();

            Assert.IsTrue(total > TimeSpan.FromSeconds(2));
            TimeSpan overalScope = jToken["Context"][0]["ElapsedTime"].ToObject <TimeSpan>();

            Assert.IsTrue(total == overalScope);
            TimeSpan innerScope = jToken["Context"][1]["ElapsedTime"].ToObject <TimeSpan>();

            Assert.IsTrue(innerScope > TimeSpan.FromSeconds(1));
        }