Beispiel #1
0
 private RefreshInstruction(ICacheRefresher refresher, RefreshMethodType refreshType)
 {
     RefresherId = refresher.RefresherUniqueId;
     RefreshType = refreshType;
     //set default - this value is not used for reading after it's been deserialized, it's only used for persisting the instruction to the db
     JsonIdCount = 1;
 }
Beispiel #2
0
        protected virtual void Deliver(IEnumerable <IServerAddress> servers, ICacheRefresher refresher, MessageType messageType, IEnumerable <object> ids = null, string json = null)
        {
            if (servers == null)
            {
                throw new ArgumentNullException("servers");
            }
            if (refresher == null)
            {
                throw new ArgumentNullException("refresher");
            }

            var serversA = servers.ToArray();
            var idsA     = ids == null ? null : ids.ToArray();

            // deliver local
            DeliverLocal(refresher, messageType, idsA, json);

            // distribute?
            if (RequiresDistributed(serversA, refresher, messageType) == false)
            {
                return;
            }

            // deliver remote
            DeliverRemote(serversA, refresher, messageType, idsA, json);
        }
        protected override void DeliverRemote(
            IEnumerable <IServerAddress> servers,
            ICacheRefresher refresher,
            MessageType messageType,
            IEnumerable <object> ids = null,
            string json = null)
        {
            var idsA = ids == null ? null : ids.ToArray();

            Type idType;

            if (GetArrayType(idsA, out idType) == false)
            {
                throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids");
            }

            var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json);

            var dto = new CacheInstructionDto
            {
                UtcStamp         = DateTime.UtcNow,
                Instructions     = JsonConvert.SerializeObject(instructions, Formatting.None),
                OriginIdentity   = LocalIdentity,
                InstructionCount = instructions.Sum(x => x.JsonIdCount)
            };

            ApplicationContext.DatabaseContext.Database.Insert(dto);
        }
        protected virtual void Deliver <T>(ICacheRefresher refresher, MessageType messageType, Func <T, object> getId, IEnumerable <T> instances)
        {
            if (refresher == null)
            {
                throw new ArgumentNullException(nameof(refresher));
            }

            var instancesA = instances.ToArray();

            // deliver local
            DeliverLocal(refresher, messageType, getId, instancesA);

            // distribute?
            if (RequiresDistributed(refresher, messageType) == false)
            {
                return;
            }

            // deliver remote

            // map ByInstance to ById as there's no remote instances
            if (messageType == MessageType.RefreshByInstance)
            {
                messageType = MessageType.RefreshById;
            }
            if (messageType == MessageType.RemoveByInstance)
            {
                messageType = MessageType.RemoveById;
            }

            // convert instances to identifiers
            var idsA = instancesA.Select(getId).ToArray();

            DeliverRemote(refresher, messageType, idsA);
        }
Beispiel #5
0
        protected void BatchMessage(
            IEnumerable <IServerAddress> servers,
            ICacheRefresher refresher,
            MessageType messageType,
            IEnumerable <object> ids = null,
            Type idType = null,
            string json = null)
        {
            var batch        = GetBatch(true);
            var instructions = RefreshInstruction.GetInstructions(refresher, messageType, ids, idType, json);

            // batch if we can, else write to DB immediately
            if (batch == null)
            {
                //only write the json blob with a maximum count of the MaxProcessingInstructionCount
                using (var scope = _appContext.ScopeProvider.CreateScope())
                {
                    foreach (var maxBatch in instructions.InGroupsOf(Options.MaxProcessingInstructionCount))
                    {
                        WriteInstructions(scope, maxBatch);
                    }
                    scope.Complete();
                }
            }
            else
            {
                batch.Add(new RefreshInstructionEnvelope(servers, refresher, instructions));
            }
        }
        protected override void DeliverRemote(
            ICacheRefresher refresher,
            MessageType messageType,
            IEnumerable <object> ids = null,
            string json = null)
        {
            var idsA = ids?.ToArray();

            if (GetArrayType(idsA, out var idType) == false)
            {
                throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids));
            }

            var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json);

            var dto = new CacheInstructionDto
            {
                UtcStamp         = DateTime.UtcNow,
                Instructions     = JsonConvert.SerializeObject(instructions, Formatting.None),
                OriginIdentity   = LocalIdentity,
                InstructionCount = instructions.Sum(x => x.JsonIdCount)
            };

            using (var scope = ScopeProvider.CreateScope())
            {
                scope.Database.Insert(dto);
                scope.Complete();
            }
        }
        private void MessageSeversForManyObjects <T>(
            IEnumerable <IServerAddress> servers,
            ICacheRefresher refresher,
            MessageType dispatchType,
            Func <T, object> getId,
            IEnumerable <T> instances)
        {
            if (servers == null)
            {
                throw new ArgumentNullException("servers");
            }
            if (refresher == null)
            {
                throw new ArgumentNullException("refresher");
            }

            EnsureLazyUsernamePasswordDelegateResolved();

            //Now, check if we are using Distrubuted calls. If there are no servers in the list then we
            // can definitely not distribute.
            if (!_useDistributedCalls || !servers.Any())
            {
                //if we are not, then just invoke the call on the cache refresher
                InvokeMethodOnRefresherInstance(refresher, dispatchType, getId, instances);
                return;
            }

            //if we are distributing calls then we'll need to do it by id
            MessageSeversForIdsOrJson(servers, refresher, dispatchType, instances.Select(getId));
        }
Beispiel #8
0
        //protected abstract void DeliverRemote(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, object payload);

        protected virtual void Deliver(IEnumerable <IServerAddress> servers, ICacheRefresher refresher, object payload)
        {
            if (servers == null)
            {
                throw new ArgumentNullException("servers");
            }
            if (refresher == null)
            {
                throw new ArgumentNullException("refresher");
            }

            var serversA = servers.ToArray();

            // deliver local
            DeliverLocal(refresher, payload);

            // distribute?
            if (RequiresDistributed(serversA, refresher, MessageType.RefreshByJson) == false)
            {
                return;
            }

            // deliver remote
            var json = JsonConvert.SerializeObject(payload);

            DeliverRemote(serversA, refresher, MessageType.RefreshByJson, null, json);
        }
 public UserContentService(
     UserContentRepository <TUserContent, TUserContentDTO> userContentRepository,
     ICacheRefresher cacheRefresher)
 {
     _userRepo       = userContentRepository;
     _cacheRefresher = cacheRefresher;
 }
        private void InvokeMethodOnRefresherInstance <T>(ICacheRefresher refresher, MessageType dispatchType, Func <T, object> getId, IEnumerable <T> instances)
        {
            if (refresher == null)
            {
                throw new ArgumentNullException("refresher");
            }

            LogHelper.Debug <DefaultServerMessenger>("Invoking refresher {0} on single server instance, message type {1}",
                                                     () => refresher.GetType(),
                                                     () => dispatchType);

            var stronglyTypedRefresher = refresher as ICacheRefresher <T>;

            foreach (var instance in instances)
            {
                //if we are not, then just invoke the call on the cache refresher
                switch (dispatchType)
                {
                case MessageType.RefreshAll:
                    refresher.RefreshAll();
                    break;

                case MessageType.RefreshById:
                    if (stronglyTypedRefresher != null)
                    {
                        stronglyTypedRefresher.Refresh(instance);
                    }
                    else
                    {
                        var id = getId(instance);
                        if (id is int)
                        {
                            refresher.Refresh((int)id);
                        }
                        else if (id is Guid)
                        {
                            refresher.Refresh((Guid)id);
                        }
                        else
                        {
                            throw new InvalidOperationException("The id must be either an int or a Guid");
                        }
                    }
                    break;

                case MessageType.RemoveById:
                    if (stronglyTypedRefresher != null)
                    {
                        stronglyTypedRefresher.Remove(instance);
                    }
                    else
                    {
                        var id = getId(instance);
                        refresher.Refresh((int)id);
                    }
                    break;
                }
            }
        }
        public void PerformRefreshAll(ICacheRefresher refresher)
        {
            if (refresher == null)
            {
                throw new ArgumentNullException(nameof(refresher));
            }

            Deliver(refresher, MessageType.RefreshAll);
        }
Beispiel #12
0
        private UserContentContext(
            ILogger logger,
            IRuntimeCacheProvider runtimeCacheProvider)
        {
            _logger = logger;

            Instances = new Dictionary <string, IUserContentInstance>();
            refresher = new UserContentCacheRefresher(runtimeCacheProvider);
        }
Beispiel #13
0
        private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher)
        {
            if (refresher is not IJsonCacheRefresher jsonRefresher)
            {
                throw new InvalidOperationException("Cache refresher with ID \"" + refresher.RefresherUniqueId + "\" does not implement " + typeof(IJsonCacheRefresher) + ".");
            }

            return(jsonRefresher);
        }
Beispiel #14
0
        private void RefreshByIds(CacheRefresherCollection cacheRefreshers, Guid uniqueIdentifier, string jsonIds)
        {
            ICacheRefresher refresher = GetRefresher(cacheRefreshers, uniqueIdentifier);

            foreach (var id in JsonConvert.DeserializeObject <int[]>(jsonIds))
            {
                refresher.Refresh(id);
            }
        }
        private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher)
        {
            var jsonRefresher = refresher as IJsonCacheRefresher;

            if (jsonRefresher == null)
            {
                throw new InvalidOperationException("Cache refresher with ID \"" + refresher.UniqueIdentifier + "\" does not implement " + typeof(IJsonCacheRefresher) + ".");
            }
            return(jsonRefresher);
        }
Beispiel #16
0
 internal UserContentInstance(DatabaseContext databaseContext,
                              string tableName,
                              ICacheRefresher refresher,
                              IRuntimeCacheProvider cacheProvider)
 {
     Repository = new UserContentRepository <TUserContent, TUserContentDTO>(databaseContext, tableName);
     Service    = new UserContentService <TUserContent, TUserContentDTO>(
         (UserContentRepository <TUserContent, TUserContentDTO>)Repository, refresher);
     Cache = cacheProvider;
 }
Beispiel #17
0
        // helper method to get an ICacheRefresher by its unique identifier
        private ICacheRefresher GetRefresherById(Guid refresherGuid)
        {
            ICacheRefresher refresher = _cacheRefreshers[refresherGuid];

            if (refresher == null)
            {
                throw new InvalidOperationException($"No cache refresher found with id {refresherGuid}");
            }

            return(refresher);
        }
Beispiel #18
0
        private ICacheRefresher GetRefresher(CacheRefresherCollection cacheRefreshers, Guid id)
        {
            ICacheRefresher refresher = cacheRefreshers[id];

            if (refresher == null)
            {
                throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist.");
            }

            return(refresher);
        }
        /// <inheritdoc/>
        protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable <object> ids = null, string json = null)
        {
            var idsA = ids?.ToArray();

            if (GetArrayType(idsA, out Type arrayType) == false)
            {
                throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids));
            }

            BatchMessage(refresher, messageType, idsA, arrayType, json);
        }
Beispiel #20
0
        public FeedRepository(ApplicationDbContext context, IMemoryCache cache, ICacheRefresher cacheRefresher)
        {
            _context = context ?? throw new NullReferenceException();

            _cache          = cache;
            _cacheRefresher = cacheRefresher;
            if (!_cache.TryGetValue("Feeds", out List <Feed> feedsCollections))
            {
                var a = _cache.Get("Feeds");
                _cacheRefresher.Refresh();
            }
        }
Beispiel #21
0
 public OrderValidationService(ICacheRefresher cacheRefresher,
                               ICache <Order> orderCache,
                               ICache <SubscriptionModel> subCache,
                               ICache <PurchasedReportModel> prCache,
                               ILogger <OrderValidationService> logger)
 {
     _cacheRefresher = cacheRefresher;
     _orderCache     = orderCache;
     _subCache       = subCache;
     _prCache        = prCache;
     _logger         = logger;
 }
Beispiel #22
0
 private RefreshInstruction(ICacheRefresher refresher, RefreshMethodType refreshType, string json)
     : this(refresher, refreshType)
 {
     if (refreshType == RefreshMethodType.RefreshByJson)
     {
         JsonPayload = json;
     }
     else
     {
         JsonIds = json;
     }
 }
Beispiel #23
0
        public CollectionRepository(ApplicationDbContext context, IMemoryCache cache, ICacheRefresher cacheRefresher)
        {
            _context = context ?? throw new NullReferenceException();

            _cache          = cache;
            _cacheRefresher = cacheRefresher;

            if (!_cache.TryGetValue("UserCollections", out List <UserCollection> userCollections))
            {
                _cacheRefresher.Refresh();
            }
        }
        public void PerformRefresh(ICacheRefresher refresher, string jsonPayload)
        {
            if (refresher == null)
            {
                throw new ArgumentNullException(nameof(refresher));
            }
            if (jsonPayload == null)
            {
                throw new ArgumentNullException(nameof(jsonPayload));
            }

            Deliver(refresher, MessageType.RefreshByJson, json: jsonPayload);
        }
        public void PerformRefresh(ICacheRefresher refresher, params Guid[] guidIds)
        {
            if (refresher == null)
            {
                throw new ArgumentNullException(nameof(refresher));
            }
            if (guidIds == null || guidIds.Length == 0)
            {
                return;
            }

            Deliver(refresher, MessageType.RefreshById, guidIds.Cast <object>());
        }
        public void PerformRefresh <TPayload>(ICacheRefresher refresher, TPayload[] payload)
        {
            if (refresher == null)
            {
                throw new ArgumentNullException(nameof(refresher));
            }
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            Deliver(refresher, payload);
        }
        public void PerformRemove(ICacheRefresher refresher, params int[] numericIds)
        {
            if (refresher == null)
            {
                throw new ArgumentNullException(nameof(refresher));
            }
            if (numericIds == null || numericIds.Length == 0)
            {
                return;
            }

            Deliver(refresher, MessageType.RemoveById, numericIds.Cast <object>());
        }
Beispiel #28
0
        protected override void DeliverRemote(IEnumerable <IServerAddress> servers, ICacheRefresher refresher, MessageType messageType, IEnumerable <object> ids = null, string json = null)
        {
            var idsA = ids == null ? null : ids.ToArray();

            Type arrayType;

            if (GetArrayType(idsA, out arrayType) == false)
            {
                throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids");
            }

            BatchMessage(servers, refresher, messageType, idsA, arrayType, json);
        }
Beispiel #29
0
        /// <summary>
        /// Gets all ICacheRefreshers
        /// </summary>
        /// <returns></returns>
        public ICacheRefresher[] GetAll()
        {
            ICacheRefresher[] retVal = new ICacheRefresher[_refreshers.Count];
            int c = 0;

            foreach (ICacheRefresher cr in _refreshers.Values)
            {
                retVal[c] = GetNewObject(cr.UniqueIdentifier);
                c++;
            }

            return(retVal);
        }
Beispiel #30
0
        public void PerformRefreshAll(IEnumerable <IServerAddress> servers, ICacheRefresher refresher)
        {
            if (servers == null)
            {
                throw new ArgumentNullException("servers");
            }
            if (refresher == null)
            {
                throw new ArgumentNullException("refresher");
            }

            Deliver(servers, refresher, MessageType.RefreshAll);
        }
 void ProcessRefreshAll(ICacheRefresher refresher)
 {
     refresher.RefreshAll();
 }
        void ProcessRefreshById(Notification notification, ICacheRefresher refresher)
        {
            foreach (var id in _payloadService.Deserialize<object>(notification.Payload))
            {
                if (id is long)
                    refresher.Refresh(Convert.ToInt32((long)id));

                if (id is Guid)
                    refresher.Refresh((Guid)id);
            }
        }
 void ProcessRefreshJson(Notification notification, ICacheRefresher refresher)
 {
     //Tricky As IJsonCacheRefresher Is Marked As Internal
     var refresh = refresher.GetType().GetMethod("Refresh", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(string) }, null);
     if (refresh == null)
         throw new NotSupportedException("Cache Refresher Does Not Implement IJsonCacheRefresher");
     refresh.Invoke(refresher, new object[] { notification.Payload });
 }
 void ProcessRemoveById(Notification notification, ICacheRefresher refresher)
 {
     foreach (var id in _payloadService.Deserialize<int>(notification.Payload))
         refresher.Remove(id);
 }