public async Task QueryRequestOptionsSessionToken()
        {
            const string       SessionToken = "SessionToken";
            ItemRequestOptions options      = new ItemRequestOptions
            {
                SessionToken = SessionToken
            };

            TestHandler testHandler = new TestHandler((request, cancellationToken) =>
            {
                Assert.AreEqual(SessionToken, request.Headers.GetValues(HttpConstants.HttpHeaders.SessionToken).First());
                return(TestHandler.ReturnSuccess());
            });

            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();

            RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null)
            {
                InnerHandler = testHandler
            };
            RequestMessage requestMessage = new RequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"));

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType   = ResourceType.Document;
            requestMessage.OperationType  = OperationType.Read;
            requestMessage.RequestOptions = options;
            await invoker.SendAsync(requestMessage, new CancellationToken());
        }
        public async Task InvalidPartitionExceptionRetryHandlerDoesNotRetryOn410()
        {
            CosmosClient client = MockDocumentClient.CreateMockCosmosClient();

            NamedCacheRetryHandler retryHandler = new NamedCacheRetryHandler(client);
            int         handlerCalls            = 0;
            int         expectedHandlerCalls    = 2;
            TestHandler testHandler             = new TestHandler((request, cancellationToken) => {
                if (handlerCalls == 0)
                {
                    handlerCalls++;
                    return(TestHandler.ReturnStatusCode((HttpStatusCode)StatusCodes.Gone, SubStatusCodes.NameCacheIsStale));
                }

                handlerCalls++;
                return(TestHandler.ReturnSuccess());
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Get, new Uri("https://dummy.documents.azure.com:443/dbs"));
            await invoker.SendAsync(requestMessage, new CancellationToken());

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
        private async Task RetryHandlerDontRetryOnStatusCode(
            HttpStatusCode statusCode,
            SubStatusCodes subStatusCode = SubStatusCodes.Unknown)
        {
            int         handlerCalls = 0;
            TestHandler testHandler  = new TestHandler((request, response) => {
                handlerCalls++;

                if (handlerCalls == 0)
                {
                    return(TestHandler.ReturnStatusCode(statusCode, subStatusCode));
                }

                return(TestHandler.ReturnSuccess());
            });

            CosmosClient client       = MockDocumentClient.CreateMockCosmosClient();
            RetryHandler retryHandler = new RetryHandler(client.DocumentClient.ResetSessionTokenRetryPolicy);

            retryHandler.InnerHandler = testHandler;

            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Delete, RetryHandlerTests.TestUri);

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());

            int expectedHandlerCalls = 1;

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
        public async Task PartitionKeyRangeGoneRetryHandlerOn410()
        {
            CosmosClient client = MockDocumentClient.CreateMockCosmosClient();

            int         handlerCalls = 0;
            TestHandler testHandler  = new TestHandler((request, response) => {
                if (handlerCalls == 0)
                {
                    handlerCalls++;
                    return(TestHandler.ReturnStatusCode((HttpStatusCode)StatusCodes.Gone, SubStatusCodes.PartitionKeyRangeGone));
                }

                handlerCalls++;
                return(TestHandler.ReturnSuccess());
            });

            PartitionKeyRangeGoneRetryHandler retryHandler = new PartitionKeyRangeGoneRetryHandler(client);

            retryHandler.InnerHandler = testHandler;

            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Get, new Uri("https://localhost/dbs/db1/colls/col1/docs/doc1"));
            await invoker.SendAsync(requestMessage, new CancellationToken());

            int expectedHandlerCalls = 2;

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
        public async Task RetryHandlerDoesNotRetryOnSuccess()
        {
            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();

            RetryHandler retryHandler         = new RetryHandler(client);
            int          handlerCalls         = 0;
            int          expectedHandlerCalls = 1;
            TestHandler  testHandler          = new TestHandler((request, cancellationToken) => {
                handlerCalls++;
                return(TestHandler.ReturnSuccess());
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null);

            invoker.InnerHandler = retryHandler;
            RequestMessage requestMessage = new RequestMessage(HttpMethod.Delete, RetryHandlerTests.TestUri);

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
        public async Task RetryHandlerDoesNotRetryOnException()
        {
            CosmosClient client = MockDocumentClient.CreateMockCosmosClient();

            RetryHandler retryHandler         = new RetryHandler(client.DocumentClient.ResetSessionTokenRetryPolicy);
            int          handlerCalls         = 0;
            int          expectedHandlerCalls = 2;
            TestHandler  testHandler          = new TestHandler((request, cancellationToken) => {
                handlerCalls++;
                if (handlerCalls == expectedHandlerCalls)
                {
                    Assert.Fail("Should not retry on exception.");
                }

                throw new Exception("You shall not retry.");
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"));

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());
        }
        public async Task RetryHandlerRetriesOn429()
        {
            CosmosClient client = MockDocumentClient.CreateMockCosmosClient();

            RetryHandler retryHandler         = new RetryHandler(client.DocumentClient.ResetSessionTokenRetryPolicy);
            int          handlerCalls         = 0;
            int          expectedHandlerCalls = 2;
            TestHandler  testHandler          = new TestHandler((request, cancellationToken) => {
                if (handlerCalls == 0)
                {
                    handlerCalls++;
                    return(TestHandler.ReturnStatusCode((HttpStatusCode)StatusCodes.TooManyRequests));
                }

                handlerCalls++;
                return(TestHandler.ReturnSuccess());
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Delete, RetryHandlerTests.TestUri);

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
        public async Task RequestOptionsHandlerCanHandleRequestOptions()
        {
            const string PropertyKey = "propkey";
            const string Condition = "*";
            object propertyValue = Encoding.UTF8.GetBytes("test");
            RequestOptions options = new ItemRequestOptions
            {
                Properties = new Dictionary<string, object>(new List<KeyValuePair<string, object>> {
                    new KeyValuePair<string, object>(PropertyKey, propertyValue)
                }),
                IfMatchEtag = Condition,
            };

            TestHandler testHandler = new TestHandler((request, cancellationToken) =>
            {
                Assert.AreEqual(propertyValue, request.Properties[PropertyKey]);
                Assert.AreEqual(Condition, request.Headers.GetValues(HttpConstants.HttpHeaders.IfMatch).First());
                return TestHandler.ReturnSuccess();
            });

            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();

            RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null)
            {
                InnerHandler = testHandler
            };
            RequestMessage requestMessage = new RequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"));
            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            requestMessage.RequestOptions = options;

            await invoker.SendAsync(requestMessage, new CancellationToken());
        }
        public async Task ConsistencyLevelClient()
        {
            List<Cosmos.ConsistencyLevel> cosmosLevels = Enum.GetValues(typeof(Cosmos.ConsistencyLevel)).Cast<Cosmos.ConsistencyLevel>().ToList();
            foreach (Cosmos.ConsistencyLevel clientLevel in cosmosLevels)
            {
                using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(
                   accountConsistencyLevel: Cosmos.ConsistencyLevel.Strong,
                   customizeClientBuilder: builder => builder.WithConsistencyLevel(clientLevel));

                TestHandler testHandler = new TestHandler((request, cancellationToken) =>
                {
                    Assert.AreEqual(clientLevel.ToString(), request.Headers[HttpConstants.HttpHeaders.ConsistencyLevel]);
                    return TestHandler.ReturnSuccess();
                });

                RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: client.ClientOptions.ConsistencyLevel)
                {
                    InnerHandler = testHandler
                };

                RequestMessage requestMessage = new RequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"))
                {
                    ResourceType = ResourceType.Document
                };
                requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
                requestMessage.OperationType = OperationType.Read;

                await invoker.SendAsync(requestMessage, new CancellationToken());
            }
        }
        public async Task ConsistencyLevelClientAndRequestOption()
        {
            Cosmos.ConsistencyLevel requestOptionLevel = Cosmos.ConsistencyLevel.BoundedStaleness;
            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(
                accountConsistencyLevel: Cosmos.ConsistencyLevel.Strong,
                customizeClientBuilder: builder => builder.WithConsistencyLevel(Cosmos.ConsistencyLevel.Eventual));

            TestHandler testHandler = new TestHandler((request, cancellationToken) =>
            {
                Assert.AreEqual(requestOptionLevel.ToString(), request.Headers[HttpConstants.HttpHeaders.ConsistencyLevel]);
                return TestHandler.ReturnSuccess();
            });

            RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null)
            {
                InnerHandler = testHandler
            };

            RequestMessage requestMessage = new RequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"))
            {
                ResourceType = ResourceType.Document
            };
            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.OperationType = OperationType.Read;
            requestMessage.RequestOptions = new ItemRequestOptions() { ConsistencyLevel = requestOptionLevel };

            await invoker.SendAsync(requestMessage, new CancellationToken());
        }
        public async Task InvalidPartitionExceptionRetryHandlerDoesNotRetryOnSuccess()
        {
            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();

            NamedCacheRetryHandler retryHandler = new NamedCacheRetryHandler();
            int         handlerCalls            = 0;
            int         expectedHandlerCalls    = 1;
            TestHandler testHandler             = new TestHandler((request, cancellationToken) => {
                handlerCalls++;
                return(TestHandler.ReturnSuccess());
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(
                client,
                requestedClientConsistencyLevel: null)
            {
                InnerHandler = retryHandler
            };
            RequestMessage requestMessage = new RequestMessage(
                HttpMethod.Get,
                new Uri("https://dummy.documents.azure.com:443/dbs"));
            await invoker.SendAsync(requestMessage, new CancellationToken());

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
        public async Task RequestOptionsHandlerCanHandleDataPlaneRequestOptions()
        {
            const string Condition = "*";
            const string SessionToken = "test";
            ItemRequestOptions options = new ItemRequestOptions
            {
                IfNoneMatchEtag = Condition,
                ConsistencyLevel = (Cosmos.ConsistencyLevel)ConsistencyLevel.Eventual,
                SessionToken = SessionToken
            };

            TestHandler testHandler = new TestHandler((request, cancellationToken) =>
            {
                Assert.AreEqual(Condition, request.Headers.GetValues(HttpConstants.HttpHeaders.IfNoneMatch).First());
                Assert.AreEqual(ConsistencyLevel.Eventual.ToString(), request.Headers.GetValues(HttpConstants.HttpHeaders.ConsistencyLevel).First());
                Assert.AreEqual(SessionToken, request.Headers.GetValues(HttpConstants.HttpHeaders.SessionToken).First());
                return TestHandler.ReturnSuccess();
            });

            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();

            RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null)
            {
                InnerHandler = testHandler
            };
            RequestMessage requestMessage = new RequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"));
            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            requestMessage.RequestOptions = options;
            await invoker.SendAsync(requestMessage, new CancellationToken());
        }
        public async Task RequestOptionsConsistencyLevel()
        {
            List <Cosmos.ConsistencyLevel>    cosmosLevels   = Enum.GetValues(typeof(Cosmos.ConsistencyLevel)).Cast <Cosmos.ConsistencyLevel>().ToList();
            List <Documents.ConsistencyLevel> documentLevels = Enum.GetValues(typeof(Documents.ConsistencyLevel)).Cast <Documents.ConsistencyLevel>().ToList();

            CollectionAssert.AreEqual(cosmosLevels, documentLevels, new EnumComparer(), "Document consistency level is different from cosmos consistency level");

            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(accountConsistencyLevel: Cosmos.ConsistencyLevel.Strong);

            foreach (Cosmos.ConsistencyLevel level in cosmosLevels)
            {
                List <RequestOptions> requestOptions = new List <RequestOptions>
                {
                    new ItemRequestOptions
                    {
                        ConsistencyLevel = level
                    },

                    new QueryRequestOptions
                    {
                        ConsistencyLevel = level
                    },

                    new StoredProcedureRequestOptions
                    {
                        ConsistencyLevel = level
                    }
                };

                foreach (RequestOptions option in requestOptions)
                {
                    TestHandler testHandler = new TestHandler((request, cancellationToken) =>
                    {
                        Assert.AreEqual(level.ToString(), request.Headers[HttpConstants.HttpHeaders.ConsistencyLevel]);
                        return(TestHandler.ReturnSuccess());
                    });

                    RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null)
                    {
                        InnerHandler = testHandler
                    };

                    RequestMessage requestMessage = new RequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"))
                    {
                        ResourceType = ResourceType.Document
                    };
                    requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
                    requestMessage.OperationType  = OperationType.Read;
                    requestMessage.RequestOptions = option;

                    await invoker.SendAsync(requestMessage, new CancellationToken());
                }
            }
        }
示例#14
0
 internal ClientContextCore(
     CosmosClient client,
     CosmosClientOptions clientOptions,
     CosmosSerializerCore serializerCore,
     CosmosResponseFactory cosmosResponseFactory,
     RequestInvokerHandler requestHandler,
     DocumentClient documentClient)
 {
     this.Client          = client;
     this.ClientOptions   = clientOptions;
     this.SerializerCore  = serializerCore;
     this.ResponseFactory = cosmosResponseFactory;
     this.RequestHandler  = requestHandler;
     this.DocumentClient  = documentClient;
 }
        internal static async Task <T> ProcessResourceOperationAsync <T>(
            RequestInvokerHandler requestHandler,
            string resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            RequestOptions requestOptions,
            ContainerInternal cosmosContainerCore,
            FeedRange feedRange,
            Stream streamPayload,
            Action <RequestMessage> requestEnricher,
            Func <ResponseMessage, T> responseCreator,
            ITrace trace,
            CancellationToken cancellationToken)
        {
            if (requestHandler == null)
            {
                throw new ArgumentException(nameof(requestHandler));
            }

            if (resourceUri == null)
            {
                throw new ArgumentNullException(nameof(resourceUri));
            }

            if (responseCreator == null)
            {
                throw new ArgumentNullException(nameof(responseCreator));
            }

            if (trace == null)
            {
                throw new ArgumentNullException(nameof(trace));
            }

            ResponseMessage response = await requestHandler.SendAsync(
                resourceUri,
                resourceType,
                operationType,
                requestOptions,
                cosmosContainerCore,
                feedRange,
                streamPayload,
                requestEnricher,
                trace,
                cancellationToken);

            return(responseCreator(response));
        }
        internal static CosmosClientContext Create(
            CosmosClient cosmosClient,
            DocumentClient documentClient,
            CosmosClientOptions clientOptions,
            RequestInvokerHandler requestInvokerHandler = null)
        {
            if (cosmosClient == null)
            {
                throw new ArgumentNullException(nameof(cosmosClient));
            }

            if (documentClient == null)
            {
                throw new ArgumentNullException(nameof(documentClient));
            }

            clientOptions = ClientContextCore.CreateOrCloneClientOptions(clientOptions);

            if (requestInvokerHandler == null)
            {
                //Request pipeline
                ClientPipelineBuilder clientPipelineBuilder = new ClientPipelineBuilder(
                    cosmosClient,
                    clientOptions.ConsistencyLevel,
                    clientOptions.CustomHandlers);

                requestInvokerHandler = clientPipelineBuilder.Build();
            }

            CosmosSerializerCore serializerCore = CosmosSerializerCore.Create(
                clientOptions.Serializer,
                clientOptions.SerializerOptions);

            // This sets the serializer on client options which gives users access to it if a custom one is not configured.
            clientOptions.SetSerializerIfNotConfigured(serializerCore.GetCustomOrDefaultSerializer());

            CosmosResponseFactoryInternal responseFactory = new CosmosResponseFactoryCore(serializerCore);

            return(new ClientContextCore(
                       client: cosmosClient,
                       clientOptions: clientOptions,
                       serializerCore: serializerCore,
                       cosmosResponseFactory: responseFactory,
                       requestHandler: requestInvokerHandler,
                       documentClient: documentClient,
                       userAgent: documentClient.ConnectionPolicy.UserAgentContainer.UserAgent,
                       batchExecutorCache: new BatchAsyncContainerExecutorCache()));
        }
示例#17
0
        internal static CosmosClientContext Create(
            CosmosClient cosmosClient,
            DocumentClient documentClient,
            CosmosClientOptions clientOptions,
            RequestInvokerHandler requestInvokerHandler = null)
        {
            if (cosmosClient == null)
            {
                throw new ArgumentNullException(nameof(cosmosClient));
            }

            if (documentClient == null)
            {
                throw new ArgumentNullException(nameof(documentClient));
            }

            clientOptions = ClientContextCore.CreateOrCloneClientOptions(clientOptions);

            if (requestInvokerHandler == null)
            {
                //Request pipeline
                ClientPipelineBuilder clientPipelineBuilder = new ClientPipelineBuilder(
                    cosmosClient,
                    clientOptions.ConsistencyLevel,
                    clientOptions.CustomHandlers);

                requestInvokerHandler = clientPipelineBuilder.Build();
            }

            CosmosSerializerCore serializerCore = CosmosSerializerCore.Create(
                clientOptions.Serializer,
                clientOptions.SerializerOptions);

            CosmosResponseFactory responseFactory = new CosmosResponseFactory(serializerCore);

            return(new ClientContextCore(
                       client: cosmosClient,
                       clientOptions: clientOptions,
                       serializerCore: serializerCore,
                       cosmosResponseFactory: responseFactory,
                       requestHandler: requestInvokerHandler,
                       documentClient: documentClient,
                       userAgent: documentClient.ConnectionPolicy.UserAgentContainer.UserAgent,
                       encryptionProcessor: new EncryptionProcessor(),
                       dekCache: new DekCache(),
                       batchExecutorCache: new BatchAsyncContainerExecutorCache()));
        }
        public async Task RetryHandlerHttpClientExceptionRefreshesLocations()
        {
            DocumentClient dc     = new MockDocumentClient(RetryHandlerTests.TestUri, "test");
            CosmosClient   client = new CosmosClient(
                RetryHandlerTests.TestUri.OriginalString,
                Guid.NewGuid().ToString(),
                new CosmosClientOptions(),
                dc);

            Mock <IDocumentClientRetryPolicy> mockClientRetryPolicy = new Mock <IDocumentClientRetryPolicy>();

            mockClientRetryPolicy.Setup(m => m.ShouldRetryAsync(It.IsAny <Exception>(), It.IsAny <CancellationToken>()))
            .Returns <Exception, CancellationToken>((ex, tooken) => Task.FromResult(ShouldRetryResult.RetryAfter(TimeSpan.FromMilliseconds(1))));

            Mock <IRetryPolicyFactory> mockRetryPolicy = new Mock <IRetryPolicyFactory>();

            mockRetryPolicy.Setup(m => m.GetRequestPolicy())
            .Returns(() => mockClientRetryPolicy.Object);

            RetryHandler retryHandler         = new RetryHandler(client);
            int          handlerCalls         = 0;
            int          expectedHandlerCalls = 2;
            TestHandler  testHandler          = new TestHandler((request, response) => {
                handlerCalls++;
                if (handlerCalls == expectedHandlerCalls)
                {
                    return(TestHandler.ReturnSuccess());
                }

                throw new HttpRequestException("DNS or some other network issue");
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null);

            invoker.InnerHandler = retryHandler;
            RequestMessage requestMessage = new RequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"));

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
        public async Task QueryRequestOptionsDedicatedGatewayRequestOptions()
        {
            TimeSpan maxStaleness = TimeSpan.FromMinutes(5);

            DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions = new DedicatedGatewayRequestOptions
            {
                MaxIntegratedCacheStaleness = maxStaleness
            };

            List<RequestOptions> requestOptions = new List<RequestOptions>
            {
                new ItemRequestOptions
                {
                    DedicatedGatewayRequestOptions = dedicatedGatewayRequestOptions
                },
                new QueryRequestOptions
                {
                    DedicatedGatewayRequestOptions = dedicatedGatewayRequestOptions
                },
            };

            foreach (RequestOptions option in requestOptions)
            {
                TestHandler testHandler = new TestHandler((request, cancellationToken) =>
                {
                    Assert.AreEqual(maxStaleness.TotalMilliseconds.ToString(CultureInfo.InvariantCulture), request.Headers[HttpConstants.HttpHeaders.DedicatedGatewayPerRequestCacheStaleness]);

                    return TestHandler.ReturnSuccess();
                });

                using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();

                RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null)
                {
                    InnerHandler = testHandler
                };
                RequestMessage requestMessage = new RequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"));
                requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
                requestMessage.ResourceType = ResourceType.Document;
                requestMessage.OperationType = OperationType.Read;
                requestMessage.RequestOptions = option;
                await invoker.SendAsync(requestMessage, new CancellationToken());
            }
        }
示例#20
0
 internal ClientContextCore(
     CosmosClient client,
     CosmosClientOptions clientOptions,
     CosmosSerializer userJsonSerializer,
     CosmosSerializer defaultJsonSerializer,
     CosmosResponseFactory cosmosResponseFactory,
     RequestInvokerHandler requestHandler,
     DocumentClient documentClient,
     IDocumentQueryClient documentQueryClient)
 {
     this.Client               = client;
     this.ClientOptions        = clientOptions;
     this.CosmosSerializer     = userJsonSerializer;
     this.PropertiesSerializer = defaultJsonSerializer;
     this.ResponseFactory      = cosmosResponseFactory;
     this.RequestHandler       = requestHandler;
     this.DocumentClient       = documentClient;
     this.DocumentQueryClient  = documentQueryClient;
 }
 private ClientContextCore(
     CosmosClient client,
     CosmosClientOptions clientOptions,
     CosmosSerializerCore serializerCore,
     CosmosResponseFactoryInternal cosmosResponseFactory,
     RequestInvokerHandler requestHandler,
     DocumentClient documentClient,
     string userAgent,
     BatchAsyncContainerExecutorCache batchExecutorCache)
 {
     this.client             = client;
     this.clientOptions      = clientOptions;
     this.serializerCore     = serializerCore;
     this.responseFactory    = cosmosResponseFactory;
     this.requestHandler     = requestHandler;
     this.documentClient     = documentClient;
     this.userAgent          = userAgent;
     this.batchExecutorCache = batchExecutorCache;
 }
 internal ClientContextCore(
     CosmosClient client,
     CosmosClientOptions clientOptions,
     CosmosSerializerCore serializerCore,
     CosmosResponseFactory cosmosResponseFactory,
     RequestInvokerHandler requestHandler,
     DocumentClient documentClient,
     string userAgent,
     EncryptionProcessor encryptionProcessor = null,
     DekCache dekCache = null)
 {
     this.Client              = client;
     this.ClientOptions       = clientOptions;
     this.SerializerCore      = serializerCore;
     this.ResponseFactory     = cosmosResponseFactory;
     this.RequestHandler      = requestHandler;
     this.DocumentClient      = documentClient;
     this.UserAgent           = userAgent;
     this.EncryptionProcessor = encryptionProcessor;
     this.DekCache            = dekCache;
 }
        public async Task PartitionKeyRangeGoneRetryHandlerOnSuccess()
        {
            CosmosClient client = MockDocumentClient.CreateMockCosmosClient();

            PartitionKeyRangeGoneRetryHandler retryHandler = new PartitionKeyRangeGoneRetryHandler(client);
            int         handlerCalls         = 0;
            int         expectedHandlerCalls = 1;
            TestHandler testHandler          = new TestHandler((request, cancellationToken) => {
                handlerCalls++;
                return(TestHandler.ReturnSuccess());
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Get, new Uri("https://dummy.documents.azure.com:443/dbs"));
            await invoker.SendAsync(requestMessage, new CancellationToken());

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
示例#24
0
        internal static async Task <T> ProcessResourceOperationAsync <T>(
            RequestInvokerHandler requestHandler,
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            RequestOptions requestOptions,
            CosmosContainerCore cosmosContainerCore,
            Object partitionKey,
            Stream streamPayload,
            Action <CosmosRequestMessage> requestEnricher,
            Func <CosmosResponseMessage, T> responseCreator,
            CancellationToken cancellationToken)
        {
            if (requestHandler == null)
            {
                throw new ArgumentException(nameof(requestHandler));
            }

            if (resourceUri == null)
            {
                throw new ArgumentNullException(nameof(resourceUri));
            }

            if (responseCreator == null)
            {
                throw new ArgumentNullException(nameof(responseCreator));
            }

            CosmosResponseMessage response = await requestHandler.SendAsync(
                resourceUri,
                resourceType,
                operationType,
                requestOptions,
                cosmosContainerCore,
                partitionKey,
                streamPayload,
                requestEnricher);

            return(responseCreator(response));
        }
        internal static CosmosClientContext Create(
            CosmosClient cosmosClient,
            DocumentClient documentClient,
            CosmosClientOptions clientOptions,
            RequestInvokerHandler requestInvokerHandler = null)
        {
            if (cosmosClient == null)
            {
                throw new ArgumentNullException(nameof(cosmosClient));
            }

            if (documentClient == null)
            {
                throw new ArgumentNullException(nameof(documentClient));
            }

            clientOptions = ClientContextCore.CreateOrCloneClientOptions(clientOptions);

            ConnectionPolicy connectionPolicy = clientOptions.GetConnectionPolicy(cosmosClient.ClientId);
            ClientTelemetry  telemetry        = null;

            if (connectionPolicy.EnableClientTelemetry)
            {
                try
                {
                    telemetry = ClientTelemetry.CreateAndStartBackgroundTelemetry(
                        documentClient: documentClient,
                        userAgent: connectionPolicy.UserAgentContainer.UserAgent,
                        connectionMode: connectionPolicy.ConnectionMode,
                        authorizationTokenProvider: cosmosClient.AuthorizationTokenProvider,
                        diagnosticsHelper: DiagnosticsHandlerHelper.Instance,
                        preferredRegions: clientOptions.ApplicationPreferredRegions);
                }
                catch (Exception ex)
                {
                    DefaultTrace.TraceInformation($"Error While starting Telemetry Job : {ex.Message}. Hence disabling Client Telemetry");
                    connectionPolicy.EnableClientTelemetry = false;
                }
            }
            else
            {
                DefaultTrace.TraceInformation("Client Telemetry Disabled.");
            }

            if (requestInvokerHandler == null)
            {
                //Request pipeline
                ClientPipelineBuilder clientPipelineBuilder = new ClientPipelineBuilder(
                    cosmosClient,
                    clientOptions.ConsistencyLevel,
                    clientOptions.CustomHandlers,
                    telemetry: telemetry);

                requestInvokerHandler = clientPipelineBuilder.Build();
            }

            CosmosSerializerCore serializerCore = CosmosSerializerCore.Create(
                clientOptions.Serializer,
                clientOptions.SerializerOptions);

            // This sets the serializer on client options which gives users access to it if a custom one is not configured.
            clientOptions.SetSerializerIfNotConfigured(serializerCore.GetCustomOrDefaultSerializer());

            CosmosResponseFactoryInternal responseFactory = new CosmosResponseFactoryCore(serializerCore);

            return(new ClientContextCore(
                       client: cosmosClient,
                       clientOptions: clientOptions,
                       serializerCore: serializerCore,
                       cosmosResponseFactory: responseFactory,
                       requestHandler: requestInvokerHandler,
                       documentClient: documentClient,
                       userAgent: documentClient.ConnectionPolicy.UserAgentContainer.UserAgent,
                       batchExecutorCache: new BatchAsyncContainerExecutorCache(),
                       telemetry: telemetry));
        }