Ejemplo n.º 1
0
 /// <summary>
 /// Fluently sets logic
 /// </summary>
 /// <param name="host"></param>
 /// <param name="logic"></param>
 /// <returns></returns>
 public static IEndPointHost HasLogic(this IEndPointHost host, LogicOfTo<string, string> logic)
 {
     Condition.Requires(host).IsNotNull();
     Condition.Requires(logic).IsNotNull();
     host.Logic = logic;
     return host;
 }
Ejemplo n.º 2
0
        public override List<IHasId> Search(LogicOfTo<IHasId,bool> filter)
        {
            if (!this.AllowedOperations.Has(StoreOperation.Search))
                throw new InvalidOperationException("operation masked");

            return this.Decorated.Search(filter);
        }
Ejemplo n.º 3
0
        public Host(EndPoint ep, LogicOfTo<string, string> logic= null, Func<System.Net.IPEndPoint, bool> validateClientEndPointStrategy = null)
            : base(ep, logic)
        {
            this.ValidateClientEndPointStrategy = validateClientEndPointStrategy;

            this.Initialize();
            this.Start();
        }
 public FactoriedEvictingInMemoryStore(LogicOfTo<IStoredObjectId, IHasId> factory, 
     LogicOfTo<IHasId, ICondition> defaultItemEvictionConditionFactory, 
     double backgroundIntervalMSecs = 30000)
     : base(NaturalInMemoryStore.New()
     .DecorateWithEviction(NaturalInMemoryStore.New(), 
     defaultItemEvictionConditionFactory, backgroundIntervalMSecs)
     .DecorateWithFactory(factory))
 {
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes
        /// </summary>
        /// <param name="ep"></param>
        /// <param name="strategy"></param>
        public EndPointHostBase(EndPoint ep, LogicOfTo<string,string> logic = null)
            : base()
        {
            Condition.Requires(ep).IsNotNull();

            //validate the ep is within the current ip list
            var ips = NetUtil.GetLocalIPAddresses();
            Condition.Requires(ips).Contains(ep.IPAddress);

            this.EndPoint = ep;
            this.Logic = logic;
        }
Ejemplo n.º 6
0
        public void SetBitLogic(string name, Func <IHasId, bool> hasBitLogic, int index = -1)
        {
            lock (this._stateLock)
            {
                Condition.Requires(name).IsNotNullOrEmpty();
                Condition.Requires(hasBitLogic).IsNotNull();

                //DO A GENERAL VALIDATION OF LIST INTEGRITY
                //get all the bitlogic items
                var bitLogics = this.StoreOfBitLogic.GetAll().OrderBy(x => x.Id).ToArray();

                //validate they're all sequential starting from zero
                for (int i = 0; i < bitLogics.Length; i++)
                {
                    var each = bitLogics[i];
                    //validate an entry exists
                    Condition.Requires(each).IsNotNull("null bit entry @ " + i);
                    //validate the indexes are consistent
                    Condition.Requires(each.Id.ToString()).IsEqualTo(i.ToString(), "index mismatch @ " + i);
                }
                //OK WE'RE VALID

                //set the item
                IndexingBitLogic storeItem = null;
                //if specifying index, it must be existing or next new
                if (index >= 0)
                {
                    Condition.Requires(index).IsLessOrEqual(bitLogics.Length, "out of range index");

                    //build the new item
                    storeItem = IndexingBitLogic.New(LogicOfTo <IHasId, bool> .New(hasBitLogic).HasId <int>(index).HasName(name));
                }
                else if (index == -1)
                {
                    //build the new item
                    storeItem = IndexingBitLogic.New(LogicOfTo <IHasId, bool> .New(hasBitLogic).HasId <int>(bitLogics.Length).HasName(name));
                }
                else
                {
                    throw new ArgumentOutOfRangeException("index");
                }

                //save the store item
                this.StoreOfBitLogic.SaveItem(storeItem);
            }
        }
Ejemplo n.º 7
0
        public EvictingDecoration(IStore decorated,
            IStore expirableStore,
            LogicOfTo<IHasId, IExpirable> expirableFactory,
            double backgroundIntervalMSecs = 30000)
            : base(decorated.Polls())
        {
            Condition.Requires(expirableStore).IsNotNull();
            Condition.Requires(expirableFactory).IsNotNull();

            this.ExpirableStore = expirableStore;
            this.ExpirableFactory = expirableFactory;

            var poller = this.GetPoll();
            poller.SetBackgroundAction(LogicOf<IStore>.New((reg) =>
            {
                this.Evict();
            }), backgroundIntervalMSecs);
        }
Ejemplo n.º 8
0
        public override List <IHasId> Search(LogicOfTo <IHasId, bool> filter)
        {
            this.Logger.LogVerbose("Search started", null);

            try
            {
                return(Decorated.Search(filter));
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex.Message, null, ex);
                throw;
            }
            finally
            {
                this.Logger.LogVerbose("Search completed", null);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// given a nodestore finds the current node's parent node
        /// </summary>
        /// <param name="nodeStore"></param>
        /// <returns></returns>
        public static GraphNode GetParentNode(this IStoreOf <GraphNode> nodeStore, GraphPath path)
        {
            Condition.Requires(nodeStore).IsNotNull();

            GraphNode rv = null;

            //if we're on a root node, there is no parent
            if (path.IsRoot)
            {
                return(null);
            }

            var parentPath = path.ParentPath;
            var matches    = nodeStore.SearchOf(LogicOfTo <GraphNode, bool> .New((x) => { return(x.Id.Equals(parentPath)); }));

            rv = matches.FirstOrDefault();
            return(rv);
        }
Ejemplo n.º 10
0
        public HostTest()
            : base(LogicOf <Host> .New((x) =>
        {
            //give the host echo logic
            x.HasLogic(LogicOfTo <string, string> .New((req) => { return(req); }));
            //start the host
            x.Start();

            //build a client
            var client = Client.New(x.EndPoint);

            //send some data
            var reqDat = "Hello world";
            var dat    = client.Send(reqDat);
            Condition.Requires(dat).IsEqualTo(reqDat);
        }))
        {
        }
Ejemplo n.º 11
0
        public EvictingDecoration(IStore decorated,
                                  IStore expirableStore,
                                  LogicOfTo <IHasId, IExpirable> expirableFactory,
                                  double backgroundIntervalMSecs = 30000)
            : base(decorated.Polls())
        {
            Condition.Requires(expirableStore).IsNotNull();
            Condition.Requires(expirableFactory).IsNotNull();

            this.ExpirableStore   = expirableStore;
            this.ExpirableFactory = expirableFactory;

            var poller = this.GetPoll();

            poller.SetBackgroundAction(LogicOf <IStore> .New((reg) =>
            {
                this.Evict();
            }), backgroundIntervalMSecs);
        }
Ejemplo n.º 12
0
        private void PerformOperation(IStore requestStore, IStore responseStore)
        {
            Condition.Requires(requestStore).IsNotNull();
            Condition.Requires(responseStore).IsNotNull();

            var  req    = requestStore.Get <OperationArg>(this.Id);
            TArg reqObj = (TArg)req.Data;

            try
            {
                LogicOfTo <TArg, TResult> logic = (LogicOfTo <TArg, TResult>) this.OperationLogic;

                var respLogic = logic.Perform(reqObj) as LogicOfTo <TArg, TResult>;
                responseStore.SaveItem(OperationResult.New(this.Id, respLogic.Result));
            }
            catch (Exception ex)
            {
                responseStore.SaveItem(OperationError.New(this.Id, ex));
            }
        }
        public StoreProtocolHostDecoration(IEndPointHost decorated, LogicOf <Tuple <IStore, IStore> > storeProtocolLogic, ValueManagerChainOfResponsibility valueManager = null)
            : base(decorated)
        {
            Condition.Requires(storeProtocolLogic).IsNotNull();
            this.StoreProtocolLogic = storeProtocolLogic;
            if (valueManager == null)
            {
                this.ValueManager = ValueManagerChainOfResponsibility.NewDefault();
            }
            else
            {
                this.ValueManager = valueManager;
            }

            //replace the logic
            this.Logic = LogicOfTo <string, string> .New((request) =>
            {
                return(this.HandleStoreProtocolRequest(request));
            });
        }
Ejemplo n.º 14
0
        public static List <T> GetAll <T>(this ISearchableStore store) where T : IHasId
        {
            if (store == null)
            {
                return(null);
            }

            LogicOfTo <IHasId, bool> filter = new LogicOfTo <IHasId, bool>((item) =>
            {
                if (!(item is T))
                {
                    return(false);
                }

                return(true);
            });

            var list = store.Search(filter);

            return(list.ConvertListTo <T, IHasId>());
        }
Ejemplo n.º 15
0
 public CompositeTokenizerDecoration(IForwardMovingTokenizer <T> decorated,
                                     IRoutingTokenizer <T> router = null,
                                     LogicOfTo <ForwardMovingTokenizingCursor <T>, int> lengthStrategy   = null,
                                     LogicOfTo <ForwardMovingTokenizingCursor <T>, object> stateStrategy = null)
     : base(decorated)
 {
     if (router == null)
     {
         this.Router = NaturallyNotImplementedForwardMovingTokenizer <T> .New().HasId("composite router").MakeRouter();
     }
     else
     {
         this.Router = router;
     }
     if (lengthStrategy == null)
     {
         //do a router parse and see how far we go
         this.LengthStrategy = LogicOfTo <ForwardMovingTokenizingCursor <T>, int> .New(cursor =>
         {
             int newPos;
             var vals = this.routerParse(cursor.Source, cursor.CurrentPosition, cursor.State, cursor.CurrentToken, out newPos);
             return(newPos);
         });
     }
     else
     {
         this.LengthStrategy = lengthStrategy;
     }
     if (stateStrategy == null)
     {
         this.StateStrategy = LogicOfTo <ForwardMovingTokenizingCursor <T>, object> .New(cursor =>
         {
             return(null);
         });
     }
     else
     {
         this.StateStrategy = stateStrategy;
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// returns true if the trigger changes state
        /// </summary>
        /// <param name="trigger"></param>
        /// <returns></returns>
        public bool Trigger(string trigger)
        {
            lock (this._stateLock)
            {
                //does this transition from the current state exist?
                LogicOfTo <StringStateTransition, bool> filter = LogicOfTo <StringStateTransition, bool> .New((x) =>
                {
                    return(x.FromState.Equals(this.CurrentState) && x.TransitionTrigger.Equals(trigger));
                });

                var list = this.Store.SearchOf <StringStateTransition>(filter);

                if (list == null || list.Count == 0)
                {
                    return(false);
                }

                var toState = list.FirstOrDefault();
                this.SetCurrentState(toState.ToState);
                return(true);
            }
        }
Ejemplo n.º 17
0
        public override List <IHasId> Search(LogicOfTo <IHasId, bool> filter)
        {
            //execute it
            var uow = this.SearchOperationIntercept.Perform(filter);

            if (uow.Error != null)
            {
                var errorStack = string.Join(Environment.NewLine, uow.LogEntries.ToArray());
                this.Logger.LogError("intercept error", errorStack, uow.Error);

                throw new InvalidOperationException("intercept error", uow.Error);
            }

            List <IHasId> returnValue = new List <IHasId>();

            //convert to list of T
            uow.ProcessedResult.WithEach(x =>
            {
                returnValue.Add((IHasId)x);
            });
            return(returnValue);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// filters out non-type items, and those that don't pass the explicit filter
        /// </summary>
        public static List <IHasId> SearchOf(this ISearchableStore store, Type type, LogicOfTo <IHasId, bool> filter)
        {
            if (store == null)
            {
                return(null);
            }

            LogicOfTo <IHasId, bool> filter2 = new LogicOfTo <IHasId, bool>((item) =>
            {
                if (!type.IsAssignableFrom(item.GetType()))
                {
                    return(false);
                }

                LogicOfTo <IHasId, bool> logic = filter.Perform(item) as LogicOfTo <IHasId, bool>;
                return(logic.Result);
            });

            var list = store.Search(filter2);

            return(list);
        }
Ejemplo n.º 19
0
        public static IForwardMovingTokenizer <T> HasPairDelimitedLengthStrategy <T>(this IForwardMovingTokenizer <T> decorated,
                                                                                     T[] prefix, T[] suffix)
        {
            Condition.Requires(decorated).IsNotNull();
            Condition.Requires(prefix).IsNotNull().IsNotEmpty();
            Condition.Requires(suffix).IsNotNull().IsNotEmpty();

            var lengthStrategy = LogicOfTo <ForwardMovingTokenizingCursor <T>, int> .New(x =>
            {
                var pos = x.Source.GetPositionOfComplement(prefix, suffix, x.CurrentPosition);
                var rv  = pos - x.CurrentPosition;

                if (rv <= 0)
                {
                    return(0);
                }
                return(rv);
            });

            return(new HasLengthStrategyTokenizerDecoration <T>(decorated, lengthStrategy).HasValidation());
            //NOTE: good practice is to add validation fluently after any decoration that introduces a handling condition
        }
Ejemplo n.º 20
0
        public virtual List <IHasId> Search(LogicOfTo <IHasId, bool> filter)
        {
            Condition.Requires(filter).IsNotNull();

            List <IHasId> returnValue = new List <IHasId>();

            //#if DEBUG
            //            Debug.WriteLine(string.Format("Id:{0}  Thread:{1}  Type:{2} Store search starts", (this as IHasId).With(o => o.Id).With(o => o.ToString()), Thread.CurrentThread.ManagedThreadId, this.GetType().FullName));
            //#endif

            //lock and retrieve the values
            List <IHasId> vals = new List <IHasId>();

            lock (this._stateLock)
            {
                vals.AddRange(this.Dictionary.Values);
            }

            vals.WithEach(x =>
            {
                //if the item is the wrong type, skip it
                LogicOfTo <IHasId, bool> logic = filter.Perform(x) as LogicOfTo <IHasId, bool>;
                if (logic.Result)
                {
                    returnValue.Add(x);
                }
            });

            //#if DEBUG
            //            returnValue.WithEach(x =>
            //            {
            //                Debug.WriteLine(string.Format("Id:{0}  Thread:{1}  Type:{2} Store search returns {3}", (this as IHasId).With(o => o.Id).With(o => o.ToString()), Thread.CurrentThread.ManagedThreadId, this.GetType().FullName, x.GetStoredObjectId().ToString()));
            //            });
            //            Debug.WriteLine(string.Format("Id:{0}  Thread:{1}  Type:{2} Store search ends", (this as IHasId).With(o => o.Id).With(o => o.ToString()), Thread.CurrentThread.ManagedThreadId, this.GetType().FullName));

            //#endif

            return(returnValue);
        }
Ejemplo n.º 21
0
        public virtual List<IHasId> Search(LogicOfTo<IHasId, bool> filter)
        {
            Condition.Requires(filter).IsNotNull();

            List<IHasId> returnValue = new List<IHasId>();

            //#if DEBUG
            //            Debug.WriteLine(string.Format("Id:{0}  Thread:{1}  Type:{2} Store search starts", (this as IHasId).With(o => o.Id).With(o => o.ToString()), Thread.CurrentThread.ManagedThreadId, this.GetType().FullName));
            //#endif

            //lock and retrieve the values
            List<IHasId> vals = new List<IHasId>();
            lock (this._stateLock)
            {
                vals.AddRange(this.Dictionary.Values);
            }

            vals.WithEach(x =>
            {
                //if the item is the wrong type, skip it
                LogicOfTo<IHasId, bool> logic = filter.Perform(x) as LogicOfTo<IHasId, bool>;
                if(logic.Result)
                {
                    returnValue.Add(x);
                }
            });

            //#if DEBUG
            //            returnValue.WithEach(x =>
            //            {
            //                Debug.WriteLine(string.Format("Id:{0}  Thread:{1}  Type:{2} Store search returns {3}", (this as IHasId).With(o => o.Id).With(o => o.ToString()), Thread.CurrentThread.ManagedThreadId, this.GetType().FullName, x.GetStoredObjectId().ToString()));
            //            });
            //            Debug.WriteLine(string.Format("Id:{0}  Thread:{1}  Type:{2} Store search ends", (this as IHasId).With(o => o.Id).With(o => o.ToString()), Thread.CurrentThread.ManagedThreadId, this.GetType().FullName));

            //#endif

            return returnValue;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// builds up the logic as an ILogic with a bunch of adjustments
        /// </summary>
        private void BuildLogicDecoration()
        {
            this.Logger.Do((x) => x.LogVerbose("BuildLogicDecoration started", null));

            var intercepts = this.Layers;

            //decorate the function
            ILogic logic = this.FunctionToIntercept;

            intercepts.WithEach((intercept) =>
            {
                if (intercept.Action != null)
                {
                    logic = logic.Adjust(LogicOfTo <ILogic, ILogic> .New((x) =>
                    {
                        return(intercept.Action);
                    }));
                }
            });
            this.DecoratedLogic = logic;

            this.Logger.Do((x) => x.LogVerbose("BuildLogicDecoration completed", null));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// filters out non-T items, and those that don't pass the explicit filter
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="store"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static List <T> SearchOf <T>(this ISearchableStore store, LogicOfTo <T, bool> filter) where T : IHasId
        {
            if (store == null)
            {
                return(null);
            }

            LogicOfTo <IHasId, bool> filter2 = new LogicOfTo <IHasId, bool>((item) =>
            {
                if (!(item is T))
                {
                    return(false);
                }

                T t = (T)item;
                LogicOfTo <T, bool> logic = filter.Perform(t) as LogicOfTo <T, bool>;
                return(logic.Result);
            });

            var list = store.Search(filter2);

            return(list.ConvertListTo <T, IHasId>());
        }
Ejemplo n.º 24
0
        public bool CanHandle(object obj, IGraph uow)
        {
            if (obj == null)
            {
                return(false);
            }

            //we can handle this if it's  a duplicate reference of something already in the node store
            var matches = uow.NodeStore.SearchOf <GraphNode>(LogicOfTo <GraphNode, bool> .New((x) =>
            {
                if (x.NodeValue == null)
                {
                    return(false);
                }

                return(object.ReferenceEquals(x.NodeValue, obj));
            }));

            if (matches != null && matches.Count > 0)
            {
                return(true);
            }
            return(false);
        }
Ejemplo n.º 25
0
 public static HasLengthStrategyTokenizerDecoration <T> New(IForwardMovingTokenizer <T> decorated, LogicOfTo <ForwardMovingTokenizingCursor <T>, int> lengthStrategy)
 {
     return(new HasLengthStrategyTokenizerDecoration <T>(decorated, lengthStrategy));
 }
Ejemplo n.º 26
0
        //#region Validation
        //public override bool Validate()
        //{
        //    bool returnValue = false;
        //    Func<string, object, string> oldStrategy = this.ServerStrategy;
        //    Func<string, object, string> echoStrategy = (req, state) =>
        //    {
        //        return req;
        //    };
        //    SimpleTCPClient client = null;
        //    //AutoResetEvent mre = new AutoResetEvent(false);
        //    //Exception trappedEx = null;

        //    try
        //    {
        //        lock (this._stateLock)
        //        {
        //            //swap out the old strategy with the echo strategy
        //            this.ServerStrategy = echoStrategy;

        //            //recycle
        //            this.Recycle();

        //            //grab a client and attempt to send a message 
        //            string data = string.Format("Validate for {0}", this.GetType().Name);

        //            client = new SimpleTCPClient(this.Address, this.Port);

        //            //sync first
        //            string resp = client.Send(data);

        //            if (resp != data) { throw new Exception("Sync echo failed"); }

        //            data = data + "1";
        //            resp = client.Send(data);

        //            if (resp != data) { throw new Exception("Sync echo failed"); }

        //            ////async
        //            //client.SendAsync(data, (socketState) =>
        //            //{
        //            //    if (socketState.ReceiveData.ToString() != data)
        //            //    {
        //            //        returnValue = false;
        //            //        trappedEx = new Exception("Async echo failed");
        //            //    }
        //            //    mre.Set();
        //            //});

        //            //mre.WaitOne();

        //            //if (trappedEx != null)
        //            //{
        //            //    throw trappedEx;
        //            //}

        //            //test the throttle
        //        }
        //        returnValue = true;
        //    }
        //    catch
        //    {
        //        returnValue = false;
        //    }
        //    finally
        //    {
        //        //swap back the old strategy
        //        this.ServerStrategy = oldStrategy;

        //        if (client != null)
        //        {
        //            client.Dispose();
        //        }

        //        //if (mre != null)
        //        //{
        //        //    mre.Dispose();
        //        //}
        //    }
        //    return returnValue;
        //}
        //#endregion

        #region Static Methods
        public static Host New(EndPoint ep, LogicOfTo<string, string> logic = null, Func<System.Net.IPEndPoint, bool> validateClientEndPointStrategy = null)
        {
            Host host = new Host(ep, logic, validateClientEndPointStrategy);
            return host;
        }
Ejemplo n.º 27
0
 public static Job New(string id, LogicOfTo<IHasId, IExpirable> evictionPolicy)
 {
     return new Job(id, evictionPolicy);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// provide store (with defined eviction strategies)
        /// </summary>
        /// <param name="store"></param>
        public Job(string id, LogicOfTo<IHasId, IExpirable> evictionPolicy)
            : base(StrategizedTask.NewBlank(id))
        {
            /*Overall process:
             * -create a managing task (this guy) to manage and store all of the subtasks.
             *  -the core of this managing task is a blank strategized core which is decorated
             *  with a bunch of behaviours that help accomplish the managing task's purpose.
             *  
             * The layers are described below:
             * -Core
             *      -PerformLogic - on perform, injects polling strategy checkTriggers() that moves the tasks along
             *      -CancelLogic - cancels all cancellable tasks
             * -Async
             *       -Complete trigger: When all tasks complete
             *       -Error trigger:When any tasks go wrong
             * -Events
             *       -OnCancelled, release waithandle
             *       -OnComplete, release waithandle
             *       -OnError, release waithandle
             * -Polling 
             *       -run checkTriggers as injected above
             * 
             * The job task also contains the TaskStore which all contains all of the tasks to manage.
             * 
             * RunToCompletion() kicks the job off and waits until it is complete.
             */

            //create new in memory store for the tasks to live in
            var taskStore = NaturalInMemoryStore.New().MakeTaskStore(evictionPolicy);
            this.TaskStore = taskStore;

            //get the core task (is also the Decorated property as we're a 2-layer cake at this point)
            StrategizedTask coreTask = this.Core as StrategizedTask;

            //define the Perform and Cancel Logic
            coreTask.Performs( Logic.New(
               () =>
               {
                   //the perform task is to turn on the polling process
                   this.As<IPollingDecoration>(false)
                       .SetBackgroundAction(LogicOf<ITask>.New(
                           (x) =>
                           {
                               this.checkTriggers();
                           })
                       );
               }));
            coreTask.Cancels( Logic.New(() => { this.CancelTasks(); }));

            //define the action to flip the waithandle that is waited on in RunToCompletion 
            Action flipWaitHandle = () =>
            {
                lock (_stateLock)
                {
                    if (this.Status == DecoratidTaskStatusEnum.Cancelled ||
            this.Status == DecoratidTaskStatusEnum.Complete ||
            this.Status == DecoratidTaskStatusEnum.Errored)
                        Monitor.Pulse(_stateLock);
                }
            };

            //now decorate this core task with the layers described above

            //decorate as asynch (under the hood this will decorate with Trigger Conditions). Also implies that we need a polling process to check the conditions
            ITask decoratedTask = coreTask.IsAsynchronous(
                        StrategizedCondition.New(() => { return this.AreTasksComplete(); }),
                        StrategizedCondition.New(() => { return this.HaveTasksErrored(); }));
            //decorate with event handlers to flip the wait handle
            decoratedTask = decoratedTask.Eventing().DoOnTaskCancelled(flipWaitHandle).DoOnTaskCompleted(flipWaitHandle).DoOnTaskErrored(flipWaitHandle);
            //decorate with polling without a polling strategy
            decoratedTask = decoratedTask.DecorateWithPolling();

            //set the task store
            decoratedTask.TaskStore = this.TaskStore;
            decoratedTask.Save();

            //inject decoration that we've just built 
            this.ReplaceDecorated((decorated) =>
            {
                return decoratedTask;
            });

            //subscribe to eviction event where we initiate a cancel if it happens
            this.TaskStore.ItemEvicted += Job_ItemEvicted;
        }
Ejemplo n.º 29
0
 public FactoryDecoration(LogicOfTo <IStoredObjectId, IHasId> factory, IStore decorated)
     : base(decorated)
 {
     Condition.Requires(factory).IsNotNull();
     this.Factory = factory;
 }
Ejemplo n.º 30
0
 public StrategizedConditionOf(LogicOfTo <T, bool?> conditionStrategy)
 {
     Condition.Requires(conditionStrategy).IsNotNull();
     this.ConditionStrategy = conditionStrategy;
 }
Ejemplo n.º 31
0
 public static StrategizedConditionOf <T> New(LogicOfTo <T, bool?> conditionStrategy)
 {
     Condition.Requires(conditionStrategy).IsNotNull();
     return(new StrategizedConditionOf <T>(conditionStrategy));
 }
Ejemplo n.º 32
0
        public Test()
            : base(LogicOf <IStore> .New((x) =>
        {
            x.Clear();
            var thing = AsId <string> .New("asId1");
            var soid  = thing.GetStoredObjectId();

            //mask commit
            IStore store = x.NoCommit();

            Assert.Throws <InvalidOperationException>(() =>
            {
                store.SaveItem(thing);
            });

            //mask get
            store = x.NoGet();
            store.SaveItem(thing);

            Assert.Throws <InvalidOperationException>(() =>
            {
                store.Get <AsId <string> >("asId1");
            });

            //mask search
            store = x.NoSearch();
            store.SaveItem(thing);
            var itemCopy = store.Get <AsId <string> >("asId1");

            Assert.Throws <InvalidOperationException>(() =>
            {
                var list = store.SearchOf <AsId <string> >(LogicOfTo <AsId <string>, bool> .New((o) => { return(o.Id.Equals("asId1")); }));
            });

            //mask getall
            store = x.NoGetAll();
            store.SaveItem(thing);
            itemCopy = store.Get <AsId <string> >("asId1");

            Assert.Throws <InvalidOperationException>(() =>
            {
                var list = store.GetAll();
            });

            //mask all of them
            store = x.NoGetAll().NoCommit().NoGet().NoSearch();

            Assert.Throws <InvalidOperationException>(() =>
            {
                store.SaveItem(thing);
            });
            Assert.Throws <InvalidOperationException>(() =>
            {
                store.Get <AsId <string> >("asId1");
            });
            Assert.Throws <InvalidOperationException>(() =>
            {
                var list = store.SearchOf <AsId <string> >(LogicOfTo <AsId <string>, bool> .New((o) => { return(o.Id.Equals("asId1")); }));
            });
            Assert.Throws <InvalidOperationException>(() =>
            {
                var list = store.GetAll();
            });

            //cleanup
            x.DeleteItem(soid);
        }))
        {
        }
        public override List<IHasId> Search(LogicOfTo<IHasId,bool> filter)
        {
            //execute it
            var uow = this.SearchOperationIntercept.Perform(filter);
            if (uow.Error != null)
            {
                var errorStack = string.Join(Environment.NewLine, uow.LogEntries.ToArray());
                this.Logger.LogError("intercept error", errorStack, uow.Error);

                throw new InvalidOperationException("intercept error", uow.Error);
            }

            List<IHasId> returnValue = new List<IHasId>();
            //convert to list of T
            uow.ProcessedResult.WithEach(x =>
            {
                returnValue.Add((IHasId)x);
            });
            return returnValue;
        }
Ejemplo n.º 34
0
        public override List<IHasId> Search(LogicOfTo<IHasId,bool> filter)
        {
            this.Logger.LogVerbose("Search started", null);

            try
            {
                return Decorated.Search(filter);
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex.Message, null, ex);
                throw;
            }
            finally
            {
                this.Logger.LogVerbose("Search completed", null);
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// adds eviction to a store. 
        /// </summary>
        /// <param name="decorated"></param>
        /// <param name="evictionConditionStore"></param>
        /// <param name="defaultItemEvictionConditionFactory"></param>
        /// <param name="backgroundIntervalMSecs"></param>
        /// <returns></returns>
        public static EvictingDecoration Evicting(this IStore decorated,
            IStore evictionConditionStore,
            LogicOfTo<IHasId, IExpirable> defaultItemEvictionConditionFactory,
            double backgroundIntervalMSecs = 30000)
        {
            Condition.Requires(decorated).IsNotNull();

            return new EvictingDecoration(decorated, evictionConditionStore, defaultItemEvictionConditionFactory, backgroundIntervalMSecs);
        }
Ejemplo n.º 36
0
 public static Job NewWithNeverExpireDefault(string id)
 {
     return(new Job(id, LogicOfTo <IHasId, IExpirable> .New((x) => { return EvictionPolicy.BuildNeverExpirable(); })));
 }
Ejemplo n.º 37
0
 public FactoryDecoration(LogicOfTo<IStoredObjectId, IHasId> factory, IStore decorated)
     : base(decorated)
 {
     Condition.Requires(factory).IsNotNull();
     this.Factory = factory;
 }
Ejemplo n.º 38
0
 public static StrategizedConditionOf <T> BuildConditionOf <T>(this LogicOfTo <T, bool?> conditionStrategy)
 {
     return(new StrategizedConditionOf <T>(conditionStrategy));
 }
Ejemplo n.º 39
0
 /// <summary>
 /// provides a factory on the get if an item doesn't exist
 /// </summary>
 /// <param name="decorated"></param>
 /// <param name="factory"></param>
 /// <returns></returns>
 public static FactoryDecoration HasFactory(this IStore decorated, LogicOfTo<IStoredObjectId, IHasId> factory)
 {
     Condition.Requires(decorated).IsNotNull();
     return new FactoryDecoration(factory, decorated);
 }
Ejemplo n.º 40
0
        public Test()
            : base(LogicOf <IStore> .New((x) =>
        {
            x.Clear();
            var thing = AsId <string> .New("asId1");
            var soid  = thing.GetStoredObjectId();

            //build cache that polls every 5 seconds and always expires whatever is in it
            var store = x.Caching(NamedNaturalInMemoryStore.New("caching store").Evicting(NamedNaturalInMemoryStore.New("eviction condition store"), LogicOfTo <IHasId, IExpirable> .New((o) =>
            {
                return(NaturalTrueExpirable.New());   //.DecorateWithDateExpirable(DateTime.Now.AddSeconds(5000));
            }), 1000));
            var isEvicted = false;
            store.CachingStore.ItemEvicted += delegate(object sender, EventArgOf <Tuple <IHasId, IExpirable> > e)
            {
                isEvicted = true;
            };
            //save
            store.SaveItem(thing);
            Thread.Sleep(6000);
            //now pull from the store, itself (not the caching store) and it will repopulate the cache
            var item = store.Get <AsId <string> >("asId1");
            Assert.True(item != null);

            //explicitly check the cache
            item = store.CachingStore.Get <AsId <string> >("asId1");
            Assert.True(item != null);

            //wait 5 seconds, and check cache again
            Thread.Sleep(6000);
            item = store.CachingStore.Get <AsId <string> >("asId1");
            Assert.True(item == null);

            //now pull from the store, itself (not the caching store) and it will repopulate the cache
            item = store.Get <AsId <string> >("asId1");
            Assert.True(item != null);

            item = store.CachingStore.Get <AsId <string> >("asId1");
            Assert.True(item != null);

            //cleanup
            store.Dispose();
        }))
        {
        }
Ejemplo n.º 41
0
 public static CompositeTokenizerDecoration <T> New(IForwardMovingTokenizer <T> decorated, IRoutingTokenizer <T> router = null,
                                                    LogicOfTo <ForwardMovingTokenizingCursor <T>, int> lengthStrategy   = null,
                                                    LogicOfTo <ForwardMovingTokenizingCursor <T>, object> stateStrategy = null)
 {
     return(new CompositeTokenizerDecoration <T>(decorated, router, lengthStrategy, stateStrategy));
 }
Ejemplo n.º 42
0
 public static NessOperation <Tness, Tres> New(string id, LogicOfTo <Arg <Tness>, Tres> logic)
 {
     return(new NessOperation <Tness, Tres>(id, logic));
 }
Ejemplo n.º 43
0
 /// <summary>
 /// decorates a store as a TaskStore so that it is capable of handling the task store responsibilities such as
 /// eviction and validation
 /// </summary>
 public static ITaskStore MakeTaskStore(this IStore store, LogicOfTo<IHasId, IExpirable> evictionPolicy)
 {
     Condition.Requires(store).IsNotNull();
     Condition.Requires(evictionPolicy).IsNotNull();
     return new TaskStoreDecoration(store, evictionPolicy);
 }
Ejemplo n.º 44
0
 public static EvictingDecoration New(IStore decorated,
     IStore expirableStore,
     LogicOfTo<IHasId, IExpirable> expirableFactory)
 {
     return new EvictingDecoration(decorated, expirableStore, expirableFactory);
 }
Ejemplo n.º 45
0
 /// <summary>
 /// provides a factory on the get if an item doesn't exist
 /// </summary>
 /// <param name="decorated"></param>
 /// <param name="factory"></param>
 /// <returns></returns>
 public static FactoryDecoration HasFactory(this IStore decorated, LogicOfTo <IStoredObjectId, IHasId> factory)
 {
     Condition.Requires(decorated).IsNotNull();
     return(new FactoryDecoration(factory, decorated));
 }
Ejemplo n.º 46
0
 public TaskStore(LogicOfTo<IHasId, IExpirable> evictionPolicy)
     :base(NaturalInMemoryStore.New(), evictionPolicy)
 {
 }
Ejemplo n.º 47
0
 public static Job New(string id, LogicOfTo <IHasId, IExpirable> evictionPolicy)
 {
     return(new Job(id, evictionPolicy));
 }
Ejemplo n.º 48
0
 public static TaskStore New(LogicOfTo<IHasId, IExpirable> evictionPolicy)
 {
     return new TaskStore(evictionPolicy);
 }
Ejemplo n.º 49
0
        /// <summary>
        /// provide store (with defined eviction strategies)
        /// </summary>
        /// <param name="store"></param>
        public Job(string id, LogicOfTo <IHasId, IExpirable> evictionPolicy)
            : base(StrategizedTask.NewBlank(id))
        {
            /*Overall process:
             * -create a managing task (this guy) to manage and store all of the subtasks.
             *  -the core of this managing task is a blank strategized core which is decorated
             *  with a bunch of behaviours that help accomplish the managing task's purpose.
             *
             * The layers are described below:
             * -Core
             *      -PerformLogic - on perform, injects polling strategy checkTriggers() that moves the tasks along
             *      -CancelLogic - cancels all cancellable tasks
             * -Async
             *       -Complete trigger: When all tasks complete
             *       -Error trigger:When any tasks go wrong
             * -Events
             *       -OnCancelled, release waithandle
             *       -OnComplete, release waithandle
             *       -OnError, release waithandle
             * -Polling
             *       -run checkTriggers as injected above
             *
             * The job task also contains the TaskStore which all contains all of the tasks to manage.
             *
             * RunToCompletion() kicks the job off and waits until it is complete.
             */

            //create new in memory store for the tasks to live in
            var taskStore = NaturalInMemoryStore.New().MakeTaskStore(evictionPolicy);

            this.TaskStore = taskStore;

            //get the core task (is also the Decorated property as we're a 2-layer cake at this point)
            StrategizedTask coreTask = this.Core as StrategizedTask;

            //define the Perform and Cancel Logic
            coreTask.Performs(Logic.New(
                                  () =>
            {
                //the perform task is to turn on the polling process
                this.As <IPollingDecoration>(false)
                .SetBackgroundAction(LogicOf <ITask> .New(
                                         (x) =>
                {
                    this.checkTriggers();
                })
                                     );
            }));
            coreTask.Cancels(Logic.New(() => { this.CancelTasks(); }));

            //define the action to flip the waithandle that is waited on in RunToCompletion
            Action flipWaitHandle = () =>
            {
                lock (_stateLock)
                {
                    if (this.Status == DecoratidTaskStatusEnum.Cancelled ||
                        this.Status == DecoratidTaskStatusEnum.Complete ||
                        this.Status == DecoratidTaskStatusEnum.Errored)
                    {
                        Monitor.Pulse(_stateLock);
                    }
                }
            };

            //now decorate this core task with the layers described above

            //decorate as asynch (under the hood this will decorate with Trigger Conditions). Also implies that we need a polling process to check the conditions
            ITask decoratedTask = coreTask.IsAsynchronous(
                StrategizedCondition.New(() => { return(this.AreTasksComplete()); }),
                StrategizedCondition.New(() => { return(this.HaveTasksErrored()); }));

            //decorate with event handlers to flip the wait handle
            decoratedTask = decoratedTask.Eventing().DoOnTaskCancelled(flipWaitHandle).DoOnTaskCompleted(flipWaitHandle).DoOnTaskErrored(flipWaitHandle);
            //decorate with polling without a polling strategy
            decoratedTask = decoratedTask.DecorateWithPolling();

            //set the task store
            decoratedTask.TaskStore = this.TaskStore;
            decoratedTask.Save();

            //inject decoration that we've just built
            this.ReplaceDecorated((decorated) =>
            {
                return(decoratedTask);
            });

            //subscribe to eviction event where we initiate a cancel if it happens
            this.TaskStore.ItemEvicted += Job_ItemEvicted;
        }
Ejemplo n.º 50
0
 public TaskStoreDecoration(IStore store, LogicOfTo<IHasId, IExpirable> evictionPolicy)
     : base(store.IsOf<ITask>().IsOfUniqueId().Evicting(NaturalInMemoryStore.New(), evictionPolicy, 1000))
 {
 }
Ejemplo n.º 51
0
 public List<ITask> SearchOf(LogicOfTo<ITask, bool> filter)
 {
     return this.SearchOf<ITask>(filter);
 }
Ejemplo n.º 52
0
        public override List<IHasId> Search(LogicOfTo<IHasId,bool> filter)
        {
            var list = this.Decorated.Search(filter);

            List<IHasId> returnValue = new List<IHasId>();

            list.WithEach(x =>
            {
                if (this.TouchExpirable(x.GetStoredObjectId()))
                    returnValue.Add(x);
            });

            return returnValue;
        }