public void PagingOnBoundStatementTest_Async_UsingConfigBasedPagingSetting()
        {
            var pageSize = 10;
            var queryOptions = new QueryOptions().SetPageSize(pageSize);
            Builder builder = new Builder().WithQueryOptions(queryOptions).WithDefaultKeyspace(KeyspaceName);
            builder.AddContactPoint(TestCluster.InitialContactPoint);

            using (ISession session = builder.Build().Connect())
            {
                var totalRowLength = 1003;
                Tuple<string, string> tableNameAndStaticKeyVal = CreateTableWithCompositeIndexAndInsert(session, totalRowLength);
                string statementToBeBound = "SELECT * from " + tableNameAndStaticKeyVal.Item1 + " where label=?";
                PreparedStatement preparedStatementWithoutPaging = session.Prepare(statementToBeBound);
                PreparedStatement preparedStatementWithPaging = session.Prepare(statementToBeBound);
                BoundStatement boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(tableNameAndStaticKeyVal.Item2);
                BoundStatement boundStatemetWithPaging = preparedStatementWithPaging.Bind(tableNameAndStaticKeyVal.Item2);

                var rsWithSessionPagingInherited = session.ExecuteAsync(boundStatemetWithPaging).Result;

                var rsWithoutPagingInherited = Session.Execute(boundStatemetWithoutPaging);

                //Check that the internal list of items count is pageSize
                Assert.AreEqual(pageSize, rsWithSessionPagingInherited.InnerQueueCount);
                Assert.AreEqual(totalRowLength, rsWithoutPagingInherited.InnerQueueCount);

                var allTheRowsPaged = rsWithSessionPagingInherited.ToList();
                Assert.AreEqual(totalRowLength, allTheRowsPaged.Count);
            }
        }
 private static Configuration GetConfig(QueryOptions queryOptions = null)
 {
     return new Configuration(new Policies(),
         new ProtocolOptions(),
         null,
         new SocketOptions(),
         new ClientOptions(),
         NoneAuthProvider.Instance,
         null,
         queryOptions ?? DefaultQueryOptions,
         new DefaultAddressTranslator());
 }
 public void RequestHandler_GetRequest_SimpleStatement_QueryOptions_Are_Used()
 {
     var stmt = new SimpleStatement("DUMMY QUERY");
     Assert.AreEqual(0, stmt.PageSize);
     Assert.Null(stmt.ConsistencyLevel);
     var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum).SetPageSize(100);
     var request = (QueryRequest)RequestHandler<RowSet>.GetRequest(stmt, 2, GetConfig(queryOptions));
     Assert.AreEqual(100, request.PageSize);
     Assert.AreEqual(queryOptions.GetPageSize(), request.PageSize);
     Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
     Assert.AreEqual(ConsistencyLevel.Any, request.SerialConsistency);
 }
 private static Session GetInstance(QueryOptions queryOptions = null)
 {
     var config = new Configuration(new Policies(),
         new ProtocolOptions(),
         null,
         new SocketOptions(),
         new ClientOptions(),
         NoneAuthProvider.Instance,
         null,
         queryOptions ?? new QueryOptions(), 
         new DefaultAddressTranslator());
     return new Session(null, config, null, 2);
 }
Example #5
0
 public LinqCommandInfo(LinqCommand command, QueryOptions options, LinqCommandFlags flags,
     List<Type> entityTypes, string cacheKey, List<ParameterExpression> externalParameters,
     List<LambdaExpression> includes)
 {
     CommandType = command.CommandType;
       CommandKind = command.Kind;
       Options = options;
       Flags = flags;
       EntityTypes = entityTypes;
       CacheKey = cacheKey;
       ExternalParameters = externalParameters;
       Includes = includes;
 }
 public void SimpleStatement_QueryOptions_Are_Used()
 {
     var stmt = new SimpleStatement("DUMMY QUERY");
     Assert.AreEqual(0, stmt.PageSize);
     Assert.Null(stmt.ConsistencyLevel);
     var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum).SetPageSize(100);
     var session = GetInstance(queryOptions);
     var request = (QueryRequest)session.GetRequest(stmt);
     Assert.AreEqual(100, request.PageSize);
     Assert.AreEqual(queryOptions.GetPageSize(), request.PageSize);
     Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
     Assert.AreEqual(ConsistencyLevel.Any, request.SerialConsistency);
 }
 //Query the crawled data by keywords. The inputs of the method are the inputs of the PI Web API correspondent action
 public Dictionary<string, dynamic> Search(string query, QueryOptions queryOption, string[] scope = null, string[] fields = null, int count = 10, int start = 0)
 {
     List<string> foundItems = new List<string>();
     string scopeQueryString = GenerateQueryString(scope, "scope");
     string fieldsQueryString = GenerateQueryString(fields, "fields");
     Url = baseUrl + "search/query?q=" + queryOption.ToString().ToLower() + ":" + query + scopeQueryString + fieldsQueryString + "&count=" + count + "&start=" + start;
     dynamic result = MakeGetRequest(Url);
     Dictionary<string, dynamic> dataDic = new Dictionary<string, dynamic>();
     foreach (dynamic item in result.Items)
     {
         dataDic.Add(item.Paths[0].Value,item);
     }
     return dataDic;
 }
        internal static GridContext Create(HttpContext context, string gridName, IMVCGridDefinition grid, QueryOptions options)
        {
            var httpContext = new HttpContextWrapper(context);
            var urlHelper = new System.Web.Mvc.UrlHelper(new RequestContext(httpContext, new RouteData()));

            var gridContext = new GridContext()
            {
                GridName = gridName,
                CurrentHttpContext = context,
                GridDefinition = grid,
                QueryOptions = options,
                UrlHelper = urlHelper
            };

            return gridContext;
        }
        public ActionResult Index()
        {
            if (IsXrdsRequest())
                return View("Xrds");

            IList<Review> reviews;
            var queryOptions = new QueryOptions<Review>
                                   {
                                       Take = 12,
                                       OrderDirection = OrderByDirection.Descending,
                                       OrderBySelector = r => r.PublicationDate
                                   };

            var user = _userService.GetCurrentUser();
            if(user != null)
                reviews = _repository.FindAll(r =>  user.IsSubscribedTo(r.ReviewType), queryOptions);
            else
                reviews = _repository.FindAll(queryOptions);

            return View(reviews);
        }
Example #10
0
 public void BatchStatement_QueryOptions_Are_Used()
 {
     var stmt = new BatchStatement();
     Assert.Null(stmt.ConsistencyLevel);
     var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum);
     var session = GetInstance(queryOptions);
     var request = (BatchRequest)session.GetRequest(stmt);
     Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
 }
 public async Task<QueryResult<PreparedQueryDefinition[]>> List(QueryOptions q)
 {
     return await _client.Get<PreparedQueryDefinition[]>("/v1/query", q).Execute().ConfigureAwait(false);
 }
        public IEnumerable<QueryRow> GetAllDocs(QueryOptions options)
        {
            var remainingIDs = default(List<string>);
            var enumerator = GetDocEnumerator(options, out remainingIDs);
            var current = 0;
            foreach(var next in enumerator) {
                if (current++ >= options.Limit) {
                    yield break;
                }

                var sequenceNumber = 0L;
                var docID = next.CurrentDocID;
                remainingIDs.Remove(docID);
                var value = default(IDictionary<string, object>);
                if (next.Exists) {
                    sequenceNumber = (long)next.SelectedRev.sequence;
                    var conflicts = default(IList<string>);
                    if (options.AllDocsMode >= AllDocsMode.ShowConflicts && next.IsConflicted) {
                        SelectCurrentRevision(next);
                        using (var innerEnumerator = new CBForestHistoryEnumerator(next, true, false)) {
                            conflicts = innerEnumerator.Select(x => (string)x.SelectedRev.revID).ToList();
                        }

                        if (conflicts.Count == 1) {
                            conflicts = null;
                        }
                    }

                    bool valid = conflicts != null || options.AllDocsMode != AllDocsMode.OnlyConflicts;
                    if (!valid) {
                        continue;
                    }

                    value = new NonNullDictionary<string, object> {
                        { "rev", next.CurrentRevID },
                        { "deleted", next.IsDeleted ? (object)true : null },
                        { "_conflicts", conflicts }
                    };
                }

                var row = new QueryRow(value == null ? null : docID, sequenceNumber, docID, value, 
                    value == null ? null : new RevisionInternal(next, options.IncludeDocs), null);
                if (options.Filter == null || options.Filter(row)) {
                    yield return row;
                }
            }

            foreach (var docId in remainingIDs) {
                var value = GetAllDocsEntry(docId);
                
                    
                var row = new QueryRow(value != null ? docId as string : null, 0, docId, value, null, null);
                if (options.Filter == null || options.Filter(row)) {
                    yield return row;
                }
            }
                
        }
        public void Should_Use_Statement_ReadTimeout()
        {
            const int generalReadTimeout = 1500;
            const int statementReadTimeout = 12000;
            var testCluster = TestClusterManager.CreateNew();
            var socketOptions = new SocketOptions().SetReadTimeoutMillis(generalReadTimeout);
            var queryOptions = new QueryOptions().SetRetryOnTimeout(false);
            var builder = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint)
                .WithSocketOptions(socketOptions)
                .WithPoolingOptions(new PoolingOptions()
                    .SetCoreConnectionsPerHost(HostDistance.Local, 1)
                    .SetHeartBeatInterval(0))
                .WithQueryTimeout(Timeout.Infinite)
                .WithQueryOptions(queryOptions);
            using (var cluster = builder.Build())
            {
                var session = cluster.Connect();
                //warmup
                TestHelper.Invoke(() => session.Execute("SELECT key FROM system.local"), 10);
                testCluster.PauseNode(1);
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                Assert.Throws<OperationTimedOutException>(() => session.Execute("SELECT key FROM system.local"));
                stopWatch.Stop();
                //precision of the timer is not guaranteed
                Assert.Greater(stopWatch.ElapsedMilliseconds, generalReadTimeout - 1000);
                Assert.Less(stopWatch.ElapsedMilliseconds, generalReadTimeout + 1000);

                //Try with an specified timeout at Statement level
                var stmt = new SimpleStatement("SELECT key FROM system.local")
                    .SetReadTimeoutMillis(statementReadTimeout);
                stopWatch.Restart();
                Assert.Throws<OperationTimedOutException>(() => session.Execute(stmt));
                stopWatch.Stop();
                //precision of the timer is not guaranteed
                Assert.Greater(stopWatch.ElapsedMilliseconds, statementReadTimeout - 3000);
                Assert.Less(stopWatch.ElapsedMilliseconds, statementReadTimeout + 3000);
                testCluster.ResumeNode(1);
            }
        }
        public static QueryOptions ParseOptions(IMVCGridDefinition grid, HttpRequest httpRequest)
        {
            string qsKeyPage = grid.QueryStringPrefix + QueryStringSuffix_Page;
            string qsKeySort = grid.QueryStringPrefix + QueryStringSuffix_Sort;
            string qsKeyDirection = grid.QueryStringPrefix + QueryStringSuffix_SortDir;
            string qsKeyEngine = grid.QueryStringPrefix + QueryStringSuffix_Engine;
            string qsKeyPageSize = grid.QueryStringPrefix + QueryStringSuffix_ItemsPerPage;
            string qsColumns = grid.QueryStringPrefix + QueryStringSuffix_Columns;

            var options = new QueryOptions();

            if (httpRequest.QueryString[qsKeyEngine] != null)
            {
                string re = httpRequest.QueryString[qsKeyEngine];
                options.RenderingEngineName = re;
            }

            if (!grid.Paging)
            {
                options.ItemsPerPage = null;
                options.PageIndex = null;
            }
            else
            {
                options.ItemsPerPage = grid.ItemsPerPage;

                if (grid.AllowChangingPageSize)
                {
                    if (httpRequest.QueryString[qsKeyPageSize] != null)
                    {
                        int pageSize;
                        if (Int32.TryParse(httpRequest.QueryString[qsKeyPageSize], out pageSize))
                        {
                            options.ItemsPerPage = pageSize;
                        }
                    }

                    if (grid.MaxItemsPerPage.HasValue && grid.MaxItemsPerPage.Value < options.ItemsPerPage)
                    {
                        options.ItemsPerPage = grid.MaxItemsPerPage.Value;
                    }
                }

                if (options.ItemsPerPage <= 0)
                {
                    options.ItemsPerPage = 20;
                }

                options.PageIndex = 0;
                if (httpRequest.QueryString[qsKeyPage] != null)
                {
                    int pageNum;
                    if (Int32.TryParse(httpRequest.QueryString[qsKeyPage], out pageNum))
                    {
                        options.PageIndex = pageNum - 1;
                        if (options.PageIndex < 0) options.PageIndex = 0;
                    }
                }
            }

            if (!grid.Filtering)
            {
                //options.Filters
            }
            else
            {
                var filterableColumns = grid.GetColumns().Where(p => p.EnableFiltering);

                foreach (var col in filterableColumns)
                {
                    string qsKey = grid.QueryStringPrefix + col.ColumnName;

                    if (httpRequest.QueryString[qsKey] != null)
                    {
                        string filterValue = httpRequest.QueryString[qsKey];

                        if (!String.IsNullOrWhiteSpace(filterValue))
                        {
                            options.Filters.Add(col.ColumnName, filterValue);
                        }
                    }
                }
            }

            if (!grid.Sorting)
            {
                options.SortColumnName = null;
                options.SortColumnData = null;
                options.SortDirection = SortDirection.Unspecified;
            }
            else
            {
                options.SortColumnName = null;

                string sortColName = null;
                if (httpRequest.QueryString[qsKeySort] != null)
                {
                    sortColName = httpRequest.QueryString[qsKeySort];
                }

                if (String.IsNullOrWhiteSpace(sortColName))
                {
                    sortColName = grid.DefaultSortColumn;
                }

                string thisSortColName = sortColName.Trim().ToLower();

                // validate SortColumn
                var colDef = grid.GetColumns().SingleOrDefault(p => p.ColumnName.ToLower() == thisSortColName);


                if (colDef != null && !colDef.EnableSorting)
                {
                    colDef = null;
                }
                

                if (colDef != null)
                {
                    options.SortColumnName = colDef.ColumnName;
                    options.SortColumnData = colDef.SortColumnData;
                }
                

                options.SortDirection = grid.DefaultSortDirection;
                if (httpRequest.QueryString[qsKeyDirection] != null)
                {
                    string sortDir = httpRequest.QueryString[qsKeyDirection];
                    if (String.Compare(sortDir, "dsc", true) == 0)
                    {
                        options.SortDirection = SortDirection.Dsc;
                    }
                    else if (String.Compare(sortDir, "asc", true) == 0)
                    {
                        options.SortDirection = SortDirection.Asc;
                    }
                }
            }

            if (grid.AdditionalQueryOptionNames.Count > 0)
            {
                foreach (var aqon in grid.AdditionalQueryOptionNames)
                {
                    string qsKeyAQO = grid.QueryStringPrefix + aqon;
                    string val = "";

                    if (httpRequest.QueryString[qsKeyAQO] != null)
                    {
                        val = httpRequest.QueryString[qsKeyAQO];
                    }

                    options.AdditionalQueryOptions.Add(aqon, val);
                }
            }

            if (grid.PageParameterNames.Count > 0)
            {
                foreach (var aqon in grid.PageParameterNames)
                {
                    string qsKeyAQO = QueryStringPrefix_PageParameter + grid.QueryStringPrefix + aqon;
                    string val = "";

                    if (httpRequest.QueryString[qsKeyAQO] != null)
                    {
                        val = httpRequest.QueryString[qsKeyAQO];
                    }

                    options.PageParameters.Add(aqon, val);
                }
            }


            var gridColumns = grid.GetColumns();
            List<ColumnVisibility> requestedColumns = new List<ColumnVisibility>();
            if (httpRequest.QueryString[qsColumns] == null)
            {
                foreach (var gridColumn in gridColumns)
                {
                    requestedColumns.Add(
                        new ColumnVisibility() {
                            ColumnName = gridColumn.ColumnName,
                            Visible = gridColumn.Visible
                        });
                }
            }
            else
            {
                string cols = httpRequest.QueryString[qsColumns];

                string[] colParts = cols.Split(',', ';');

                foreach (var colPart in colParts)
                {
                    if (String.IsNullOrWhiteSpace(colPart))
                    {
                        continue;
                    }
                    string thisColPart = colPart.ToLower().Trim();

                    var gridColumn = gridColumns.SingleOrDefault(p => p.ColumnName.ToLower() == thisColPart);

                    if (gridColumn != null)
                    {
                        if (requestedColumns.SingleOrDefault(p=>p.ColumnName== gridColumn.ColumnName) == null)
                        {
                            requestedColumns.Add(
                                new ColumnVisibility()
                                {
                                    ColumnName = gridColumn.ColumnName,
                                    Visible = true
                                });
                        }
                    }
                }
            }

            foreach (var gridColumn in gridColumns)
            {
                var requestedCol = requestedColumns.SingleOrDefault(p => p.ColumnName == gridColumn.ColumnName);

                if (requestedCol == null)
                {
                    requestedCol = new ColumnVisibility() { ColumnName = gridColumn.ColumnName, Visible = false };
                    requestedColumns.Add(requestedCol);
                }

                if (!requestedCol.Visible && gridColumn.Visible && !gridColumn.AllowChangeVisibility)
                {
                    requestedCol.Visible = true;
                }
            }
            options.ColumnVisibility.AddRange(requestedColumns);

            return options;
        }
        private CBForestDocEnumerator GetDocEnumerator(QueryOptions options, out List<string> remainingIDs)
        {
            var forestOps = options.AsC4EnumeratorOptions();
            var enumerator = default(CBForestDocEnumerator);
            remainingIDs = new List<string>();
            if(options.Keys != null) {
                try {
                    remainingIDs = options.Keys.Cast<string>().ToList();
                    enumerator = new CBForestDocEnumerator(Forest, remainingIDs.ToArray(), forestOps);
                } catch(InvalidCastException) {
                    Log.E(TAG, "options.keys must contain strings");
                    throw;
                }
            } else {
                enumerator = new CBForestDocEnumerator(Forest, options.StartKey as string, options.EndKey as string, forestOps);
            }

            return enumerator;
        }
Example #16
0
 public Task<QueryResult<PreparedQueryDefinition[]>> Get(string queryID, QueryOptions q)
 {
     return _client.Get<PreparedQueryDefinition[]>(string.Format("/v1/query/{0}", queryID), q).Execute();
 }
Example #17
0
 public Task<QueryResult<PreparedQueryDefinition[]>> List(QueryOptions q)
 {
     return _client.Get<PreparedQueryDefinition[]>("/v1/query", q).Execute();
 }
        /// <summary>
        /// Queries the specified view using the specified options
        /// </summary>
        /// <returns>The HTTP response containing the results of the query</returns>
        /// <param name="context">The request context</param>
        /// <param name="db">The database to run the query in</param>
        /// <param name="view">The view to query</param>
        /// <param name="options">The options to apply to the query</param>
        public static CouchbaseLiteResponse QueryView(ICouchbaseListenerContext context, Database db, View view, QueryOptions options)
        {
            var result = view.QueryWithOptions(options);

            object updateSeq = options.UpdateSeq ? (object)view.LastSequenceIndexed : null;
            var mappedResult = new List<object>();
            foreach (var row in result) {
                row.Database = db;
                var dict = row.AsJSONDictionary();
                if (context.ContentOptions != DocumentContentOptions.None) {
                    var doc = dict.Get("doc").AsDictionary<string, object>();
                    if (doc != null) {
                        // Add content options:
                        RevisionInternal rev = new RevisionInternal(doc);
                        var status = new Status();
                        rev = DocumentMethods.ApplyOptions(context.ContentOptions, rev, context, db, status);
                        if (rev != null) {
                            dict["doc"] = rev.GetProperties();
                        }
                    }
                }

                mappedResult.Add(dict);
            }

            var body = new Body(new NonNullDictionary<string, object> {
                { "rows", mappedResult },
                { "total_rows", view.TotalRows },
                { "offset", options.Skip },
                { "update_seq", updateSeq }
            });

            var retVal = context.CreateResponse();
            retVal.JsonBody = body;
            return retVal;
        }
Example #19
0
		public void WhenSerializing_ThenRoundrips()
		{
			var options = new QueryOptions
			{
				Content = { "foo", "bar" },
				Tag = "wpf",
				Max = 10,
				Owner = new User
				{
					Id = 5,
					Name = "kzu",
				},
			};

			var json = new UsonSerializer().Serialize(options);

			var value = new UsonSerializer().Deserialize<QueryOptions>(json);

			Assert.Equal(options.Content.Count, value.Content.Count);
			Assert.Equal(options.Tag, value.Tag);
			Assert.Equal(options.Max, value.Max);
			Assert.Equal(options.Owner.Id, value.Owner.Id);
			Assert.Equal(options.Owner.Name, value.Owner.Name);
		}
Example #20
0
 /// <summary>
 /// List is used to get the most recent events an agent has received. This list can be optionally filtered by the name. This endpoint supports quasi-blocking queries. The index is not monotonic, nor does it provide provide LastContact or KnownLeader.
 /// </summary>
 /// <param name="name">The name of the event to filter for</param>
 /// <param name="q">Customized query options</param>
 /// <returns>An array of events</returns>
 public QueryResult<UserEvent[]> List(string name, QueryOptions q)
 {
     return List(name, q, CancellationToken.None);
 }
Example #21
0
 public void BoundStatement_QueryOptions_Are_Used()
 {
     var ps = GetPrepared();
     var stmt = ps.Bind();
     Assert.AreEqual(0, stmt.PageSize);
     Assert.Null(stmt.ConsistencyLevel);
     var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum).SetPageSize(100);
     var session = GetInstance(queryOptions);
     var request = (ExecuteRequest)session.GetRequest(stmt);
     Assert.AreEqual(100, request.PageSize);
     Assert.AreEqual(queryOptions.GetPageSize(), request.PageSize);
     Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
     Assert.AreEqual(ConsistencyLevel.Any, request.SerialConsistency);
 }
 public async Task<QueryResult<PreparedQueryDefinition[]>> Get(string queryID, QueryOptions q)
 {
     return await _client.Get<PreparedQueryDefinition[]>(string.Format("/v1/query/{0}", queryID), q).Execute().ConfigureAwait(false);
 }
 public async Task<QueryResult<PreparedQueryExecuteResponse>> Execute(string queryIDOrName, QueryOptions q)
 {
     return await _client.Get<PreparedQueryExecuteResponse>(string.Format("/v1/query/{0}/execute", queryIDOrName), q).Execute().ConfigureAwait(false);
 }
Example #24
0
 private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)] ref string lpstrName, RecordType wType,
                                    QueryOptions options, int pExtra, ref IntPtr ppQueryResultsSet, int pReserved);
Example #25
0
 private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtr ppQueryResults, int pReserved);
Example #26
0
        /// <summary>
        /// Acquire attempts to reserve a slot in the semaphore, blocking until success, interrupted via CancellationToken or if an error is encountered.
        /// A provided CancellationToken can be used to abort the attempt.
        /// There is no notification that the semaphore slot has been lost, but IsHeld may be set to False at any time due to session invalidation, communication errors, operator intervention, etc.
        /// It is NOT safe to assume that the slot is held until Release() unless the Session is specifically created without any associated health checks.
        /// By default Consul sessions prefer liveness over safety and an application must be able to handle the session being lost.
        /// </summary>
        /// <param name="ct">The cancellation token to cancel semaphore acquisition</param>
        public CancellationToken Acquire(CancellationToken ct)
        {
            lock (_lock)
            {
                try
                {
                    if (IsHeld)
                    {
                        // Check if we already hold the lock
                        throw new SemaphoreHeldException();
                    }
                    // Don't overwrite the CancellationTokenSource until AFTER we've tested for holding, since there might be tasks that are currently running for this lock.
                    if (_cts.IsCancellationRequested)
                    {
                        _cts.Dispose();
                        _cts = new CancellationTokenSource();
                    }
                    _cts = new CancellationTokenSource();
                    LockSession = Opts.Session;

                    // Check if we need to create a session first
                    if (string.IsNullOrEmpty(Opts.Session))
                    {
                        try
                        {
                            Opts.Session = CreateSession();
                            _sessionRenewTask = _client.Session.RenewPeriodic(Opts.SessionTTL, Opts.Session, WriteOptions.Empty, _cts.Token);
                            LockSession = Opts.Session;
                        }
                        catch (Exception ex)
                        {
                            throw new InvalidOperationException("Failed to create session", ex);
                        }
                    }
                    else
                    {
                        LockSession = Opts.Session;
                    }

                    var contender = _client.KV.Acquire(ContenderEntry(LockSession)).Response;
                    if (!contender)
                    {
                        throw new ApplicationException("Failed to make contender entry");
                    }

                    var qOpts = new QueryOptions()
                    {
                        WaitTime = DefaultSemaphoreWaitTime
                    };

                    while (!ct.IsCancellationRequested)
                    {
                        QueryResult<KVPair[]> pairs;
                        try
                        {
                            pairs = _client.KV.List(Opts.Prefix, qOpts);
                        }
                        catch (Exception ex)
                        {
                            throw new ApplicationException("Failed to read prefix", ex);
                        }

                        var lockPair = FindLock(pairs.Response);
                        if (lockPair.Flags != SemaphoreFlagValue)
                        {
                            throw new SemaphoreConflictException();
                        }

                        var semaphoreLock = DecodeLock(lockPair);
                        if (semaphoreLock.Limit != Opts.Limit)
                        {
                            throw new SemaphoreLimitConflictException(
                                string.Format("Semaphore limit conflict (lock: {0}, local: {1})", semaphoreLock.Limit,
                                    Opts.Limit),
                                semaphoreLock.Limit, Opts.Limit);
                        }

                        PruneDeadHolders(semaphoreLock, pairs.Response);
                        if (semaphoreLock.Holders.Count >= semaphoreLock.Limit)
                        {
                            qOpts.WaitIndex = pairs.LastIndex;
                            continue;
                        }

                        semaphoreLock.Holders[LockSession] = true;

                        var newLock = EncodeLock(semaphoreLock, lockPair.ModifyIndex);

                        if (ct.IsCancellationRequested)
                        {
                            _cts.Cancel();
                            throw new TaskCanceledException();
                        }

                        // Handle the case of not getting the lock
                        if (!_client.KV.CAS(newLock).Response)
                        {
                            continue;
                        }

                        IsHeld = true;
                        _monitorTask = MonitorLock(LockSession);
                        return _cts.Token;
                    }
                    throw new SemaphoreNotHeldException("Unable to acquire the semaphore with Consul");
                }
                finally
                {
                    if (ct.IsCancellationRequested || (!IsHeld && !string.IsNullOrEmpty(Opts.Session)))
                    {
                        _cts.Cancel();
                        _client.KV.Delete(ContenderEntry(LockSession).Key);
                        if (_sessionRenewTask != null)
                        {
                            try
                            {
                                _sessionRenewTask.Wait();
                            }
                            catch (AggregateException)
                            {
                                // Ignore AggregateExceptions from the tasks during Release, since if the Renew task died, the developer will be Super Confused if they see the exception during Release.
                            }
                        }
                    }
                }
            }
        }
Example #27
0
 /// <summary>
 /// List is used to get the most recent events an agent has received. This list can be optionally filtered by the name. This endpoint supports quasi-blocking queries. The index is not monotonic, nor does it provide provide LastContact or KnownLeader.
 /// </summary>
 /// <param name="name">The name of the event to filter for</param>
 /// <param name="q">Customized query options</param>
 /// <param name="ct">Cancellation token for long poll request. If set, OperationCanceledException will be thrown if the request is cancelled before completing</param>
 /// <returns>An array of events</returns>
 public QueryResult<UserEvent[]> List(string name, QueryOptions q, CancellationToken ct)
 {
     var req = _client.CreateQuery<UserEvent[]>("/v1/event/list", q);
     if (!string.IsNullOrEmpty(name))
     {
         req.Params["name"] = name;
     }
     return req.Execute(ct);
 }
Example #28
0
        /// <summary>
        /// monitorLock is a long running routine to monitor a semaphore ownership
        /// It sets IsHeld to false if we lose our slot.
        /// </summary>
        /// <param name="lockSession">The session ID to monitor</param>
        private Task MonitorLock(string lockSession)
        {
            return Task.Run(() =>
            {
                try
                {
                    var opts = new QueryOptions() { Consistency = ConsistencyMode.Consistent };
                    while (IsHeld && !_cts.Token.IsCancellationRequested)
                    {
                        var pairs = _client.KV.List(Opts.Prefix, opts);
                        if (pairs.Response != null)
                        {
                            var lockPair = FindLock(pairs.Response);
                            var semaphoreLock = DecodeLock(lockPair);
                            PruneDeadHolders(semaphoreLock, pairs.Response);

                            // Check to see if the current session holds a semaphore slot
                            if (semaphoreLock.Holders.ContainsKey(lockSession))
                            {
                                opts.WaitIndex = pairs.LastIndex;
                            }
                            else
                            {
                                // Slot is no longer held! Shut down everything.
                                IsHeld = false;
                                _cts.Cancel();
                                return;
                            }
                        }
                        // Failsafe in case the KV store is unavailable
                        else
                        {
                            IsHeld = false;
                            _cts.Cancel();
                            return;
                        }
                    }
                }
                finally
                {
                    IsHeld = false;
                }
            });
        }
 //Do an all document request on the database (i.e. fetch all docs given some options)
 private static CouchbaseLiteResponse DoAllDocs(ICouchbaseListenerContext context, Database db, QueryOptions options)
 {
     var iterator = db.GetAllDocs(options);
     if (iterator == null) {
         return context.CreateResponse(StatusCode.BadJson);
     }
         
     var response = context.CreateResponse();
     var result = (from row in iterator
         select row.AsJSONDictionary()).ToList();
     response.JsonBody = new Body(new NonNullDictionary<string, object> {
         { "rows", result },
         { "total_rows", result.Count },
         { "offset", options.Skip },
         { "update_seq", options.UpdateSeq ? (object)db.GetLastSequenceNumber() : null }
     });
     return response;
 }
Example #30
0
 public Task<QueryResult<PreparedQueryExecuteResponse>> Execute(string queryIDOrName, QueryOptions q)
 {
     return _client.Get<PreparedQueryExecuteResponse>(string.Format("/v1/query/{0}/execute", queryIDOrName), q).Execute();
 }