Ejemplo n.º 1
0
        private async Task <CosmosContainerProperties> GetContainerSettingsAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            CosmosContainerProperties containerSettings = null;

            if (this.cosmosQueryContext.ResourceTypeEnum.IsCollectionChild())
            {
                CollectionCache collectionCache = await this.cosmosQueryContext.QueryClient.GetCollectionCacheAsync();

                using (
                    DocumentServiceRequest request = DocumentServiceRequest.Create(
                        OperationType.Query,
                        this.cosmosQueryContext.ResourceTypeEnum,
                        this.cosmosQueryContext.ResourceLink.OriginalString,
                        AuthorizationTokenType.Invalid)) //this request doesn't actually go to server
                {
                    containerSettings = await collectionCache.ResolveCollectionAsync(request, cancellationToken);
                }
            }

            if (containerSettings == null)
            {
                throw new ArgumentException($"The container was not found for resource: {this.cosmosQueryContext.ResourceLink.OriginalString} ");
            }

            return(containerSettings);
        }
        public async Task OpenAsync(
            string databaseName,
            CosmosContainerProperties collection,
            CancellationToken cancellationToken)
        {
            CollectionRoutingMap routingMap =
                await this.routingMapProvider.TryLookupAsync(collection.ResourceId, null, null, cancellationToken);

            if (routingMap == null)
            {
                return;
            }

            List<PartitionKeyRangeIdentity> ranges = routingMap.OrderedPartitionKeyRanges.Select(
                range => new PartitionKeyRangeIdentity(collection.ResourceId, range.Id)).ToList();

            List<Task> tasks = new List<Task>();

            foreach (EndpointCache endpointCache in this.addressCacheByEndpoint.Values)
            {
                tasks.Add(endpointCache.AddressCache.OpenAsync(databaseName, collection, ranges, cancellationToken));
            }

            await Task.WhenAll(tasks);
        }
Ejemplo n.º 3
0
        private ProxyDocumentQueryExecutionContext(
            IDocumentQueryExecutionContext innerExecutionContext,
            IDocumentQueryClient client,
            ResourceType resourceTypeEnum,
            Type resourceType,
            Expression expression,
            FeedOptions feedOptions,
            string resourceLink,
            CosmosContainerProperties collection,
            bool isContinuationExpected,
            Guid correlatedActivityId)
        {
            this.innerExecutionContext = innerExecutionContext;

            this.client           = client;
            this.resourceTypeEnum = resourceTypeEnum;
            this.resourceType     = resourceType;
            this.expression       = expression;
            this.feedOptions      = feedOptions;
            this.resourceLink     = resourceLink;

            this.collection             = collection;
            this.isContinuationExpected = isContinuationExpected;

            this.correlatedActivityId = correlatedActivityId;
        }
Ejemplo n.º 4
0
        public async Task ImplicitConversion()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            ContainerResponse containerResponse = await this.cosmosDatabase.GetContainer(containerName).ReadAsync();

            CosmosContainer           cosmosContainer         = containerResponse;
            CosmosContainerProperties cosmosContainerSettings = containerResponse;

            Assert.AreEqual(HttpStatusCode.NotFound, containerResponse.StatusCode);
            Assert.IsNotNull(cosmosContainer);
            Assert.IsNull(cosmosContainerSettings);

            containerResponse = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(containerName, partitionKeyPath);

            cosmosContainer         = containerResponse;
            cosmosContainerSettings = containerResponse;
            Assert.IsNotNull(cosmosContainer);
            Assert.IsNotNull(cosmosContainerSettings);

            containerResponse = await cosmosContainer.DeleteAsync();

            cosmosContainer         = containerResponse;
            cosmosContainerSettings = containerResponse;
            Assert.IsNotNull(cosmosContainer);
            Assert.IsNull(cosmosContainerSettings);
        }
Ejemplo n.º 5
0
        public void ContainerSettingsSimpleTest()
        {
            string id     = Guid.NewGuid().ToString();
            string pkPath = "/partitionKey";

            // Two equivalent definitions
            CosmosContainerProperties cosmosContainerSettings = new CosmosContainerProperties(id, pkPath);
            DocumentCollection        collection = new DocumentCollection()
            {
                Id           = id,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string>()
                    {
                        pkPath
                    },
                }
            };

            string cosmosSerialized = SettingsContractTests.CosmosSerialize(cosmosContainerSettings);
            string directSerialized = SettingsContractTests.DirectSerialize(collection);

            // Swap de-serialize and validate
            CosmosContainerProperties containerDeserSettings = SettingsContractTests.CosmosDeserialize <CosmosContainerProperties>(directSerialized);
            DocumentCollection        collectionDeser        = SettingsContractTests.DirectDeSerialize <DocumentCollection>(cosmosSerialized);

            Assert.AreEqual(collection.Id, containerDeserSettings.Id);
            Assert.AreEqual(collection.PartitionKey.Paths[0], containerDeserSettings.PartitionKeyPath);

            Assert.AreEqual(cosmosContainerSettings.Id, collectionDeser.Id);
            Assert.AreEqual(cosmosContainerSettings.PartitionKeyPath, collectionDeser.PartitionKey.Paths[0]);
        }
Ejemplo n.º 6
0
        public static ProxyDocumentQueryExecutionContext Create(
            IDocumentQueryClient client,
            ResourceType resourceTypeEnum,
            Type resourceType,
            Expression expression,
            FeedOptions feedOptions,
            string resourceLink,
            CancellationToken token,
            CosmosContainerProperties collection,
            bool isContinuationExpected,
            Guid correlatedActivityId)
        {
            token.ThrowIfCancellationRequested();
            DocumentQueryExecutionContextBase.InitParams constructorParams = new DocumentQueryExecutionContextBase.InitParams(client, resourceTypeEnum, resourceType, expression, feedOptions, resourceLink, false, correlatedActivityId);
            IDocumentQueryExecutionContext innerExecutionContext           =
                new DefaultDocumentQueryExecutionContext(constructorParams, isContinuationExpected);

            return(new ProxyDocumentQueryExecutionContext(innerExecutionContext, client,
                                                          resourceTypeEnum,
                                                          resourceType,
                                                          expression,
                                                          feedOptions,
                                                          resourceLink,
                                                          collection,
                                                          isContinuationExpected,
                                                          correlatedActivityId));
        }
        public async Task TimeToLiveTest()
        {
            string            containerName       = Guid.NewGuid().ToString();
            string            partitionKeyPath    = "/users";
            int               timeToLiveInSeconds = 10;
            ContainerResponse containerResponse   = await this.database.DefineContainer(containerName, partitionKeyPath)
                                                    .WithDefaultTimeToLive(timeToLiveInSeconds)
                                                    .CreateAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            CosmosContainer           cosmosContainer  = containerResponse;
            CosmosContainerProperties responseSettings = containerResponse;

            Assert.AreEqual(timeToLiveInSeconds, responseSettings.DefaultTimeToLive);

            ContainerResponse readResponse = await cosmosContainer.ReadAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(timeToLiveInSeconds, readResponse.Resource.DefaultTimeToLive);

            JObject itemTest = JObject.FromObject(new { id = Guid.NewGuid().ToString(), users = "testUser42" });
            ItemResponse <JObject> createResponse = await cosmosContainer.CreateItemAsync <JObject>(item : itemTest);

            JObject responseItem = createResponse;

            Assert.IsNull(responseItem["ttl"]);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
        private void Init()
        {
            this.collectionCache = new Mock <ClientCollectionCache>(new ServerStoreModel(null), null, null);
            this.collectionCache.Setup
                (m =>
                m.ResolveCollectionAsync(
                    It.IsAny <DocumentServiceRequest>(),
                    It.IsAny <CancellationToken>()
                    )
                ).Returns(Task.FromResult(CosmosContainerProperties.CreateWithResourceId("test")));

            this.partitionKeyRangeCache = new Mock <PartitionKeyRangeCache>(null, null, null);
            this.partitionKeyRangeCache.Setup(
                m => m.TryLookupAsync(
                    It.IsAny <string>(),
                    It.IsAny <CollectionRoutingMap>(),
                    It.IsAny <DocumentServiceRequest>(),
                    It.IsAny <CancellationToken>()
                    )
                ).Returns(Task.FromResult <CollectionRoutingMap>(null));


            this.globalEndpointManager = new Mock <GlobalEndpointManager>(this, new ConnectionPolicy());

            this.InitStoreModels();
        }
Ejemplo n.º 9
0
        public async Task ValidateCurrentWriteQuorumAndReplicaSetHeader()
        {
            CosmosClient   client = TestCommon.CreateCosmosClient(false);
            CosmosDatabase db     = null;

            try
            {
                db = await client.CreateDatabaseAsync(Guid.NewGuid().ToString());

                PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition {
                    Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/id" }), Kind = PartitionKind.Hash
                };
                CosmosContainerProperties containerSetting = new CosmosContainerProperties()
                {
                    Id           = Guid.NewGuid().ToString(),
                    PartitionKey = partitionKeyDefinition
                };
                CosmosContainer coll = await db.CreateContainerAsync(containerSetting);

                Document documentDefinition = new Document {
                    Id = Guid.NewGuid().ToString()
                };
                ItemResponse <Document> docResult = await coll.CreateItemAsync <Document>(documentDefinition);

                Assert.IsTrue(int.Parse(docResult.Headers[WFConstants.BackendHeaders.CurrentWriteQuorum], CultureInfo.InvariantCulture) > 0);
                Assert.IsTrue(int.Parse(docResult.Headers[WFConstants.BackendHeaders.CurrentReplicaSetSize], CultureInfo.InvariantCulture) > 0);
            }
            finally
            {
                await db.DeleteAsync();
            }
        }
Ejemplo n.º 10
0
        private async Task RefreshAsync(DocumentServiceRequest request, CancellationToken cancellationToken)
        {
            System.Diagnostics.Debug.Assert(request.IsNameBased);
            InternalCache cache            = this.GetCache(request.Headers[HttpConstants.HttpHeaders.Version]);
            string        resourceFullName = PathsHelper.GetCollectionPath(request.ResourceAddress);

            if (request.RequestContext.ResolvedCollectionRid != null)
            {
                // Here we will issue backend call only if cache wasn't already refreshed (if whatever is there corresponds to presiously resolved collection rid).
                await cache.collectionInfoByName.GetAsync(
                    resourceFullName,
                    CosmosContainerProperties.CreateWithResourceId(request.RequestContext.ResolvedCollectionRid),
                    async() =>
                {
                    DateTime currentTime = DateTime.UtcNow;
                    CosmosContainerProperties collection = await this.GetByNameAsync(request.Headers[HttpConstants.HttpHeaders.Version], resourceFullName, cancellationToken);
                    cache.collectionInfoById.Set(collection.ResourceId, collection);
                    cache.collectionInfoByNameLastRefreshTime.AddOrUpdate(resourceFullName, currentTime,
                                                                          (string currentKey, DateTime currentValue) => currentTime);
                    cache.collectionInfoByIdLastRefreshTime.AddOrUpdate(collection.ResourceId, currentTime,
                                                                        (string currentKey, DateTime currentValue) => currentTime);
                    return(collection);
                },
                    cancellationToken);
            }
            else
            {
                // In case of ForceRefresh directive coming from client, there will be no ResolvedCollectionRid, so we
                // need to refresh unconditionally.
                this.Refresh(request.ResourceAddress, request.Headers[HttpConstants.HttpHeaders.Version]);
            }

            request.RequestContext.ResolvedCollectionRid = null;
        }
        private async Task ContainerOperations(CosmosDatabase database, bool dbNotExist)
        {
            // Create should fail if the database does not exist
            if (dbNotExist)
            {
                CosmosContainerProperties newcontainerSettings = new CosmosContainerProperties(id: DoesNotExist, partitionKeyPath: "/pk");
                this.VerifyNotFoundResponse(await database.CreateContainerStreamAsync(newcontainerSettings, requestUnitsPerSecond: 500));
            }

            CosmosContainer doesNotExistContainer = database.GetContainer(DoesNotExist);

            this.VerifyNotFoundResponse(await doesNotExistContainer.ReadStreamAsync());

            CosmosContainerProperties containerSettings = new CosmosContainerProperties(id: DoesNotExist, partitionKeyPath: "/pk");

            this.VerifyNotFoundResponse(await doesNotExistContainer.ReplaceStreamAsync(containerSettings));
            this.VerifyNotFoundResponse(await doesNotExistContainer.DeleteStreamAsync());

            // Validate Child resources
            await this.ItemOperations(doesNotExistContainer, true);

            // The database exists create a container and validate it's children
            if (!dbNotExist)
            {
                CosmosContainer containerExists = await database.CreateContainerAsync(
                    id : "NotFoundTest" + Guid.NewGuid().ToString(),
                    partitionKeyPath : "/pk");

                await this.ItemOperations(containerExists, false);
            }
        }
Ejemplo n.º 12
0
        internal virtual async Task <CosmosContainerProperties> ResolveByNameAsync(
            string apiVersion,
            string resourceAddress,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            string        resourceFullName = PathsHelper.GetCollectionPath(resourceAddress);
            InternalCache cache            = this.GetCache(apiVersion);

            return(await cache.collectionInfoByName.GetAsync(
                       resourceFullName,
                       null,
                       async() =>
            {
                DateTime currentTime = DateTime.UtcNow;
                CosmosContainerProperties collection = await this.GetByNameAsync(apiVersion, resourceFullName, cancellationToken);
                cache.collectionInfoById.Set(collection.ResourceId, collection);
                cache.collectionInfoByNameLastRefreshTime.AddOrUpdate(resourceFullName, currentTime,
                                                                      (string currentKey, DateTime currentValue) => currentTime);
                cache.collectionInfoByIdLastRefreshTime.AddOrUpdate(collection.ResourceId, currentTime,
                                                                    (string currentKey, DateTime currentValue) => currentTime);
                return collection;
            },
                       cancellationToken));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Resolves a request to a collection in a sticky manner.
        /// Unless request.ForceNameCacheRefresh is equal to true, it will return the same collection.
        /// </summary>
        /// <param name="request">Request to resolve.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>Instance of <see cref="CosmosContainerProperties"/>.</returns>
        public virtual async Task <CosmosContainerProperties> ResolveCollectionAsync(
            DocumentServiceRequest request,
            CancellationToken cancellationToken)
        {
            if (request.IsNameBased)
            {
                if (request.ForceNameCacheRefresh)
                {
                    await this.RefreshAsync(request, cancellationToken);

                    request.ForceNameCacheRefresh = false;
                }

                CosmosContainerProperties collectionInfo = await this.ResolveByPartitionKeyRangeIdentityAsync(
                    request.Headers[HttpConstants.HttpHeaders.Version],
                    request.PartitionKeyRangeIdentity,
                    cancellationToken);

                if (collectionInfo != null)
                {
                    return(collectionInfo);
                }

                if (request.RequestContext.ResolvedCollectionRid == null)
                {
                    collectionInfo =
                        await this.ResolveByNameAsync(request.Headers[HttpConstants.HttpHeaders.Version], request.ResourceAddress, cancellationToken);

                    if (collectionInfo != null)
                    {
                        DefaultTrace.TraceVerbose(
                            "Mapped resourceName {0} to resourceId {1}. '{2}'",
                            request.ResourceAddress,
                            collectionInfo.ResourceId,
                            Trace.CorrelationManager.ActivityId);

                        request.ResourceId = collectionInfo.ResourceId;
                        request.RequestContext.ResolvedCollectionRid = collectionInfo.ResourceId;
                    }
                    else
                    {
                        DefaultTrace.TraceVerbose(
                            "Collection with resourceName {0} not found. '{1}'",
                            request.ResourceAddress,
                            Trace.CorrelationManager.ActivityId);
                    }

                    return(collectionInfo);
                }
                else
                {
                    return(await this.ResolveByRidAsync(request.Headers[HttpConstants.HttpHeaders.Version], request.RequestContext.ResolvedCollectionRid, cancellationToken));
                }
            }
            else
            {
                return(await this.ResolveByPartitionKeyRangeIdentityAsync(request.Headers[HttpConstants.HttpHeaders.Version], request.PartitionKeyRangeIdentity, cancellationToken) ??
                       await this.ResolveByRidAsync(request.Headers[HttpConstants.HttpHeaders.Version], request.ResourceAddress, cancellationToken));
            }
        }
Ejemplo n.º 14
0
        public async Task ContainerContractTest()
        {
            ContainerResponse response = await this.cosmosDatabase.CreateContainerAsync(new Guid().ToString(), "/id");

            Assert.IsNotNull(response);
            Assert.IsTrue(response.RequestCharge > 0);
            Assert.IsNotNull(response.Headers);
            Assert.IsNotNull(response.Headers.ActivityId);

            CosmosContainerProperties containerSettings = response.Resource;

            Assert.IsNotNull(containerSettings.Id);
            Assert.IsNotNull(containerSettings.ResourceId);
            Assert.IsNotNull(containerSettings.ETag);
            Assert.IsTrue(containerSettings.LastModified.HasValue);

            Assert.IsNotNull(containerSettings.PartitionKeyPath);
            Assert.IsNotNull(containerSettings.PartitionKeyPathTokens);
            Assert.AreEqual(1, containerSettings.PartitionKeyPathTokens.Length);
            Assert.AreEqual("id", containerSettings.PartitionKeyPathTokens[0]);

            CosmosContainerCore containerCore = response.Container as CosmosContainerCore;

            Assert.IsNotNull(containerCore);
            Assert.IsNotNull(containerCore.LinkUri);
            Assert.IsFalse(containerCore.LinkUri.ToString().StartsWith("/"));

            Assert.IsTrue(containerSettings.LastModified.Value > new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), containerSettings.LastModified.Value.ToString());
        }
Ejemplo n.º 15
0
        public void ContainerStreamDeserialzieTest()
        {
            string colId = "946ad017-14d9-4cee-8619-0cbc62414157";
            string rid   = "vu9cAA==";
            string self  = "dbs\\/vu9cAA==\\/cols\\/abc==\\/";
            string etag  = "00000000-0000-0000-f8ea-31d6e5f701d4";
            double ts    = 1555923784;

            DateTime UnixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            DateTime expected      = UnixStartTime.AddSeconds(ts);

            string testPyaload = "{\"id\":\"" + colId
                                 + "\",\"_rid\":\"" + rid
                                 + "\",\"_self\":\"" + self
                                 + "\",\"_etag\":\"" + etag
                                 + "\",\"_colls\":\"colls\\/\",\"_users\":\"users\\/\",\"_ts\":" + ts + "}";

            CosmosContainerProperties deserializedPayload =
                JsonConvert.DeserializeObject <CosmosContainerProperties>(testPyaload);

            Assert.IsTrue(deserializedPayload.LastModified.HasValue);
            Assert.AreEqual(expected, deserializedPayload.LastModified.Value);
            Assert.AreEqual(colId, deserializedPayload.Id);
            Assert.AreEqual(rid, deserializedPayload.ResourceId);
            Assert.AreEqual(etag, deserializedPayload.ETag);
        }
Ejemplo n.º 16
0
        public async Task DoubleRoundTrip()
        {
            await cosmosClient.CreateDatabaseIfNotExistsAsync(database.Id);

            Cosmos.IndexingPolicy     indexingPolicy          = IndexingPolicyTests.CreateDefaultIndexingPolicy();
            CosmosContainerProperties cosmosContainerSettings = new CosmosContainerProperties()
            {
                Id             = Guid.NewGuid().ToString(),
                IndexingPolicy = indexingPolicy,
            };

            await IndexingPolicyTests.RoundTripWithLocal(indexingPolicy);
        }
Ejemplo n.º 17
0
        public async Task NegativePartitionedCreateDelete()
        {
            string containerName = Guid.NewGuid().ToString();

            PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition();

            partitionKeyDefinition.Paths.Add("/users");
            partitionKeyDefinition.Paths.Add("/test");

            CosmosContainerProperties settings          = new CosmosContainerProperties(containerName, partitionKeyDefinition);
            ContainerResponse         containerResponse = await this.cosmosDatabase.CreateContainerAsync(settings);

            Assert.Fail("Multiple partition keys should have caused an exception.");
        }
        public async Task OpenAsync(
            string databaseName,
            CosmosContainerProperties collection,
            IReadOnlyList <PartitionKeyRangeIdentity> partitionKeyRangeIdentities,
            CancellationToken cancellationToken)
        {
            List <Task <FeedResource <Address> > > tasks = new List <Task <FeedResource <Address> > >();
            int batchSize = GatewayAddressCache.DefaultBatchSize;

#if !(NETSTANDARD15 || NETSTANDARD16)
            int userSpecifiedBatchSize = 0;
            if (int.TryParse(System.Configuration.ConfigurationManager.AppSettings[GatewayAddressCache.AddressResolutionBatchSize], out userSpecifiedBatchSize))
            {
                batchSize = userSpecifiedBatchSize;
            }
#endif

            string collectionAltLink = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}", Paths.DatabasesPathSegment, Uri.EscapeUriString(databaseName),
                                                     Paths.CollectionsPathSegment, Uri.EscapeUriString(collection.Id));
            using (DocumentServiceRequest request = DocumentServiceRequest.CreateFromName(
                       OperationType.Read,
                       collectionAltLink,
                       ResourceType.Collection,
                       AuthorizationTokenType.PrimaryMasterKey))
            {
                for (int i = 0; i < partitionKeyRangeIdentities.Count; i += batchSize)
                {
                    tasks.Add(this.GetServerAddressesViaGatewayAsync(
                                  request,
                                  collection.ResourceId,
                                  partitionKeyRangeIdentities.Skip(i).Take(batchSize).Select(range => range.PartitionKeyRangeId),
                                  false));
                }
            }

            foreach (FeedResource <Address> response in await Task.WhenAll(tasks))
            {
                IEnumerable <Tuple <PartitionKeyRangeIdentity, PartitionAddressInformation> > addressInfos =
                    response.Where(addressInfo => ProtocolFromString(addressInfo.Protocol) == this.protocol)
                    .GroupBy(address => address.PartitionKeyRangeId, StringComparer.Ordinal)
                    .Select(group => this.ToPartitionAddressAndRange(collection.ResourceId, @group.ToList()));

                foreach (Tuple <PartitionKeyRangeIdentity, PartitionAddressInformation> addressInfo in addressInfos)
                {
                    this.serverPartitionAddressCache.Set(
                        new PartitionKeyRangeIdentity(collection.ResourceId, addressInfo.Item1.PartitionKeyRangeId),
                        addressInfo.Item2);
                }
            }
        }
Ejemplo n.º 19
0
        public async Task CreateHashV1Container()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            CosmosContainerProperties settings = new CosmosContainerProperties(containerName, partitionKeyPath);

            settings.PartitionKeyDefinitionVersion = Cosmos.PartitionKeyDefinitionVersion.V1;

            ContainerResponse cosmosContainerResponse = await this.cosmosDatabase.CreateContainerAsync(settings);

            Assert.AreEqual(HttpStatusCode.Created, cosmosContainerResponse.StatusCode);

            Assert.AreEqual(Cosmos.PartitionKeyDefinitionVersion.V1, cosmosContainerResponse.Resource.PartitionKeyDefinitionVersion);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Applies the current Fluent definition and creates a container configuration.
        /// </summary>
        /// <returns>Builds the current Fluent configuration into an instance of <see cref="CosmosContainerProperties"/>.</returns>
        public virtual new CosmosContainerProperties Build()
        {
            CosmosContainerProperties settings = base.Build();

            if (this.uniqueKeyPolicy != null)
            {
                settings.UniqueKeyPolicy = this.uniqueKeyPolicy;
            }

            if (this.conflictResolutionPolicy != null)
            {
                settings.ConflictResolutionPolicy = this.conflictResolutionPolicy;
            }

            return(settings);
        }
Ejemplo n.º 21
0
        private static async Task RoundTripWithLocal(Cosmos.IndexingPolicy indexingPolicy)
        {
            PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition {
                Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/id" }), Kind = PartitionKind.Hash
            };
            CosmosContainerProperties containerSetting = new CosmosContainerProperties()
            {
                Id             = Guid.NewGuid().ToString(),
                IndexingPolicy = indexingPolicy,
                PartitionKey   = partitionKeyDefinition
            };

            CosmosDatabase cosmosDatabase = await cosmosClient.CreateDatabaseIfNotExistsAsync(IndexingPolicyTests.database.Id);

            ContainerResponse cosmosContainerResponse = await cosmosDatabase.CreateContainerAsync(containerSetting);

            Assert.IsTrue(IndexingPolicyTests.indexingPolicyEqualityComparer.Equals(indexingPolicy, containerSetting.IndexingPolicy));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Gets the list of partition key ranges.
        /// 1. Check partition key range id
        /// 2. Check Partition key
        /// 3. Check the effective partition key
        /// 4. Get the range from the PartitionedQueryExecutionInfo
        /// </summary>
        internal static async Task <List <PartitionKeyRange> > GetTargetPartitionKeyRangesAsync(
            CosmosQueryClient queryClient,
            string resourceLink,
            PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
            CosmosContainerProperties collection,
            QueryRequestOptions queryRequestOptions)
        {
            List <PartitionKeyRange> targetRanges;

            if (queryRequestOptions.PartitionKey != null)
            {
                // Dis-ambiguate the NonePK if used
                PartitionKeyInternal partitionKeyInternal = null;
                if (Object.ReferenceEquals(queryRequestOptions.PartitionKey, Cosmos.PartitionKey.NonePartitionKeyValue))
                {
                    partitionKeyInternal = collection.GetNoneValue();
                }
                else
                {
                    partitionKeyInternal = new Documents.PartitionKey(queryRequestOptions.PartitionKey.Value).InternalKey;
                }

                targetRanges = await queryClient.GetTargetPartitionKeyRangesByEpkStringAsync(
                    resourceLink,
                    collection.ResourceId,
                    partitionKeyInternal.GetEffectivePartitionKeyString(collection.PartitionKey));
            }
            else if (TryGetEpkProperty(queryRequestOptions, out string effectivePartitionKeyString))
            {
                targetRanges = await queryClient.GetTargetPartitionKeyRangesByEpkStringAsync(
                    resourceLink,
                    collection.ResourceId,
                    effectivePartitionKeyString);
            }
            else
            {
                targetRanges = await queryClient.GetTargetPartitionKeyRangesAsync(
                    resourceLink,
                    collection.ResourceId,
                    partitionedQueryExecutionInfo.QueryRanges);
            }

            return(targetRanges);
        }
        public async Task TestConflictResolutionPolicy()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            ContainerResponse containerResponse =
                await this.database.DefineContainer(containerName, partitionKeyPath)
                .WithConflictResolution()
                .WithLastWriterWinsResolution("/lww")
                .Attach()
                .CreateAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
            CosmosContainerProperties cosmosContainerSettings = containerResponse.Resource;

            Assert.IsNotNull(cosmosContainerSettings.ConflictResolutionPolicy);
            Assert.AreEqual(ConflictResolutionMode.LastWriterWins, cosmosContainerSettings.ConflictResolutionPolicy.Mode);
            Assert.AreEqual("/lww", cosmosContainerSettings.ConflictResolutionPolicy.ConflictResolutionPath);
            Assert.IsTrue(string.IsNullOrEmpty(cosmosContainerSettings.ConflictResolutionPolicy.ConflictResolutionProcedure));

            // Delete container
            await containerResponse.Container.DeleteAsync();

            // Re-create with custom policy
            string sprocName = "customresolsproc";

            containerResponse = await this.database.DefineContainer(containerName, partitionKeyPath)
                                .WithConflictResolution()
                                .WithCustomStoredProcedureResolution(sprocName)
                                .Attach()
                                .CreateAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
            cosmosContainerSettings = containerResponse.Resource;
            Assert.IsNotNull(cosmosContainerSettings.ConflictResolutionPolicy);
            Assert.AreEqual(ConflictResolutionMode.Custom, cosmosContainerSettings.ConflictResolutionPolicy.Mode);
            Assert.AreEqual(sprocName, cosmosContainerSettings.ConflictResolutionPolicy.ConflictResolutionProcedure);
            Assert.IsTrue(string.IsNullOrEmpty(cosmosContainerSettings.ConflictResolutionPolicy.ConflictResolutionPath));
        }
Ejemplo n.º 24
0
        public async Task PartitionedCRUDTest()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            ContainerResponse containerResponse = await this.cosmosDatabase.CreateContainerAsync(containerName, partitionKeyPath);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());

            CosmosContainerProperties settings = new CosmosContainerProperties(containerName, partitionKeyPath)
            {
                IndexingPolicy = new Cosmos.IndexingPolicy()
                {
                    IndexingMode = Cosmos.IndexingMode.None,
                    Automatic    = false
                }
            };

            CosmosContainer cosmosContainer = containerResponse;

            containerResponse = await cosmosContainer.ReplaceAsync(settings);

            Assert.AreEqual(HttpStatusCode.OK, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
            Assert.AreEqual(Cosmos.IndexingMode.None, containerResponse.Resource.IndexingPolicy.IndexingMode);
            Assert.IsFalse(containerResponse.Resource.IndexingPolicy.Automatic);

            containerResponse = await cosmosContainer.ReadAsync();

            Assert.AreEqual(HttpStatusCode.OK, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(Cosmos.PartitionKeyDefinitionVersion.V2, containerResponse.Resource.PartitionKeyDefinitionVersion);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
            Assert.AreEqual(Cosmos.IndexingMode.None, containerResponse.Resource.IndexingPolicy.IndexingMode);
            Assert.IsFalse(containerResponse.Resource.IndexingPolicy.Automatic);

            containerResponse = await containerResponse.Container.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Ejemplo n.º 25
0
        public void ContainerSettingsDefaults()
        {
            string id     = Guid.NewGuid().ToString();
            string pkPath = "/partitionKey";

            SettingsContractTests.TypeAccessorGuard(typeof(CosmosContainerProperties),
                                                    "Id",
                                                    "UniqueKeyPolicy",
                                                    "DefaultTimeToLive",
                                                    "IndexingPolicy",
                                                    "TimeToLivePropertyPath",
                                                    "PartitionKeyPath",
                                                    "PartitionKeyDefinitionVersion",
                                                    "ConflictResolutionPolicy");

            // Two equivalent definitions
            CosmosContainerProperties cosmosContainerSettings = new CosmosContainerProperties(id, pkPath);

            Assert.AreEqual(id, cosmosContainerSettings.Id);
            Assert.AreEqual(pkPath, cosmosContainerSettings.PartitionKeyPath);

            Assert.IsNull(cosmosContainerSettings.ResourceId);
            Assert.IsNull(cosmosContainerSettings.LastModified);
            Assert.IsNull(cosmosContainerSettings.ETag);
            Assert.IsNull(cosmosContainerSettings.DefaultTimeToLive);

            Assert.IsNotNull(cosmosContainerSettings.IndexingPolicy);
            Assert.IsNotNull(cosmosContainerSettings.ConflictResolutionPolicy);
            Assert.IsTrue(object.ReferenceEquals(cosmosContainerSettings.IndexingPolicy, cosmosContainerSettings.IndexingPolicy));
            Assert.IsNotNull(cosmosContainerSettings.IndexingPolicy.IncludedPaths);
            Assert.IsTrue(object.ReferenceEquals(cosmosContainerSettings.IndexingPolicy.IncludedPaths, cosmosContainerSettings.IndexingPolicy.IncludedPaths));

            Cosmos.IncludedPath ip = new Cosmos.IncludedPath();
            Assert.IsNotNull(ip.Indexes);

            Assert.IsNotNull(cosmosContainerSettings.UniqueKeyPolicy);
            Assert.IsTrue(object.ReferenceEquals(cosmosContainerSettings.UniqueKeyPolicy, cosmosContainerSettings.UniqueKeyPolicy));
            Assert.IsNotNull(cosmosContainerSettings.UniqueKeyPolicy.UniqueKeys);
            Assert.IsTrue(object.ReferenceEquals(cosmosContainerSettings.UniqueKeyPolicy.UniqueKeys, cosmosContainerSettings.UniqueKeyPolicy.UniqueKeys));

            Cosmos.UniqueKey uk = new Cosmos.UniqueKey();
            Assert.IsNotNull(uk.Paths);
        }
        public async Task ContainerContractTest()
        {
            ContainerResponse response =
                await this.database.DefineContainer(new Guid().ToString(), "/id")
                .CreateAsync();

            Assert.IsNotNull(response);
            Assert.IsTrue(response.RequestCharge > 0);
            Assert.IsNotNull(response.Headers);
            Assert.IsNotNull(response.Headers.ActivityId);

            CosmosContainerProperties containerSettings = response.Resource;

            Assert.IsNotNull(containerSettings.Id);
            Assert.IsNotNull(containerSettings.ResourceId);
            Assert.IsNotNull(containerSettings.ETag);
            Assert.IsTrue(containerSettings.LastModified.HasValue);

            Assert.IsTrue(containerSettings.LastModified.Value > new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), containerSettings.LastModified.Value.ToString());
        }
Ejemplo n.º 27
0
        public async Task PartitionedCreateWithPathDelete()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition();

            partitionKeyDefinition.Paths.Add(partitionKeyPath);

            CosmosContainerProperties settings          = new CosmosContainerProperties(containerName, partitionKeyDefinition);
            ContainerResponse         containerResponse = await this.cosmosDatabase.CreateContainerAsync(settings);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(containerName, containerResponse.Resource.Id);
            Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());

            containerResponse = await containerResponse.Container.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Ejemplo n.º 28
0
        public async Task TimeToLiveTest()
        {
            string containerName              = Guid.NewGuid().ToString();
            string partitionKeyPath           = "/users";
            int    timeToLiveInSeconds        = 10;
            CosmosContainerProperties setting = new CosmosContainerProperties()
            {
                Id           = containerName,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string> {
                        partitionKeyPath
                    }, Kind = PartitionKind.Hash
                },
                DefaultTimeToLive = timeToLiveInSeconds,
            };

            ContainerResponse containerResponse = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(setting);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            CosmosContainer           cosmosContainer  = containerResponse;
            CosmosContainerProperties responseSettings = containerResponse;

            Assert.AreEqual(timeToLiveInSeconds, responseSettings.DefaultTimeToLive);

            ContainerResponse readResponse = await cosmosContainer.ReadAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.AreEqual(timeToLiveInSeconds, readResponse.Resource.DefaultTimeToLive);

            JObject itemTest = JObject.FromObject(new { id = Guid.NewGuid().ToString(), users = "testUser42" });
            ItemResponse <JObject> createResponse = await cosmosContainer.CreateItemAsync <JObject>(item : itemTest);

            JObject responseItem = createResponse;

            Assert.IsNull(responseItem["ttl"]);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Ejemplo n.º 29
0
        public async Task StreamPartitionedCreateWithPathDelete()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/users";

            PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition();

            partitionKeyDefinition.Paths.Add(partitionKeyPath);

            CosmosContainerProperties settings = new CosmosContainerProperties(containerName, partitionKeyDefinition);

            using (CosmosResponseMessage containerResponse = await this.cosmosDatabase.CreateContainerStreamAsync(settings))
            {
                Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            }

            using (CosmosResponseMessage containerResponse = await this.cosmosDatabase.GetContainer(containerName).DeleteStreamAsync())
            {
                Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
            }
        }
Ejemplo n.º 30
0
        public void ContainerSettingsWithConflictResolution()
        {
            string id     = Guid.NewGuid().ToString();
            string pkPath = "/partitionKey";

            // Two equivalent definitions
            CosmosContainerProperties cosmosContainerSettings = new CosmosContainerProperties(id, pkPath)
            {
                ConflictResolutionPolicy = new Cosmos.ConflictResolutionPolicy()
                {
                    Mode = Cosmos.ConflictResolutionMode.Custom,
                    ConflictResolutionPath      = "/path",
                    ConflictResolutionProcedure = "sp"
                }
            };

            DocumentCollection collection = new DocumentCollection()
            {
                Id = id,
                ConflictResolutionPolicy = new ConflictResolutionPolicy()
                {
                    Mode = ConflictResolutionMode.Custom,
                    ConflictResolutionPath      = "/path",
                    ConflictResolutionProcedure = "sp"
                }
            };

            string cosmosSerialized = SettingsContractTests.CosmosSerialize(cosmosContainerSettings);
            string directSerialized = SettingsContractTests.DirectSerialize(collection);

            // Swap de-serialize and validate
            CosmosContainerProperties containerDeserSettings = SettingsContractTests.CosmosDeserialize <CosmosContainerProperties>(directSerialized);
            DocumentCollection        collectionDeser        = SettingsContractTests.DirectDeSerialize <DocumentCollection>(cosmosSerialized);

            Assert.AreEqual(cosmosContainerSettings.Id, collectionDeser.Id);
            Assert.AreEqual((int)cosmosContainerSettings.ConflictResolutionPolicy.Mode, (int)collectionDeser.ConflictResolutionPolicy.Mode);
            Assert.AreEqual(cosmosContainerSettings.ConflictResolutionPolicy.ConflictResolutionPath, collectionDeser.ConflictResolutionPolicy.ConflictResolutionPath);
            Assert.AreEqual(cosmosContainerSettings.ConflictResolutionPolicy.ConflictResolutionProcedure, collectionDeser.ConflictResolutionPolicy.ConflictResolutionProcedure);
        }