Beispiel #1
0
        public async Task <RegisterMigrationResponse> Register(RegisterMigrationRequest request)
        {
            var source = new CancellationTokenSource();
            var result = MigrationRegistryResult.Ok;

            source.CancelAfter(MigrationLockTimeoutDuration);

            var @lock = await _locker.AcquireAsync(request.Migration.Character.ToString(), cancellationToken : source.Token);

            if (@lock != null)
            {
                if (await _cache.ExistsAsync(request.Migration.Character.ToString()))
                {
                    result = MigrationRegistryResult.FailedAlreadyRegistered;
                }

                if (result == MigrationRegistryResult.Ok)
                {
                    await _cache.SetAsync(request.Migration.Character.ToString(), request.Migration, MigrationTimeoutDuration);
                }

                await @lock.ReleaseAsync();
            }
            else
            {
                result = MigrationRegistryResult.FailedTimeout;
            }

            return(new RegisterMigrationResponse {
                Result = result
            });
        }
Beispiel #2
0
        public async Task <bool> AddAsync <T>(T data)
        {
            if (data == null || !IsCachingServer)
            {
                return(false);
            }
            try
            {
                PropertyInfo[] properties = typeof(T).GetProperties();

                var key = Helper.GetClassName <T>() + ":" + properties[0].GetValue(data).ToString();
                Tuple.Create(key, data);
                //Find key
                if (await Sut.ExistsAsync(key))
                {
                    if (await Sut.RemoveAsync(key))
                    {
                        LogManager.Logger.LogError(new Exception("Error when remove object " + Helper.GetClassName <T>() + "- Key: " + key));
                        return(false);
                    }
                }
                //Add
                return(await Sut.AddAsync(key, data));
            }
            catch (Exception ex)
            {
                LogManager.Logger.LogError(ex);
                return(false);
            }
        }
Beispiel #3
0
        public async Task <InviteRegisterResponse> Register(InviteRegisterRequest request)
        {
            var source = new CancellationTokenSource();
            var result = InviteServiceResult.Ok;

            source.CancelAfter(InviteLockTimeoutDuration);

            var @lock = await _locker.AcquireAsync(request.Invite.Invited.ToString(), cancellationToken : source.Token);

            if (@lock != null)
            {
                var key = $"{request.Invite.Invited}:{request.Invite.Type}";

                if (await _cache.ExistsAsync(key))
                {
                    result = InviteServiceResult.FailedAlreadyInvited;
                }

                if (result == InviteServiceResult.Ok)
                {
                    await _cache.SetAsync(key, request.Invite, InviteTimeoutDuration);
                }

                await @lock.ReleaseAsync();
            }
            else
            {
                result = InviteServiceResult.FailedTimeout;
            }

            return(new InviteRegisterResponse {
                Result = result
            });
        }
Beispiel #4
0
        public async Task <TermModel> GetTermAsync(ClientContext clientContext, string termSetId, string termId)
        {
            var termCacheKey = TermCacheKey(termSetId, termId);

            if (!await _cacheClient.ExistsAsync(termCacheKey))
            {
                var termSetModel = await GetTermSetAsync(clientContext, termSetId);

                return(termSetModel.FlatTerms.FirstOrDefault(t => t.Id.Equals(termId)));
            }

            return((await _cacheClient.GetAsync <TermModel>(termCacheKey)).Value);
        }
Beispiel #5
0
        public async Task <bool> IsEnabled(ICacheClient client, ulong id)
        {
            if (Module != null)
            {
                if (!await Module.IsEnabled(client, id))
                {
                    return(false);
                }
            }

            if (await client.ExistsAsync(GetCacheKey(id)))
            {
                return(await client.GetAsync <bool>(GetCacheKey(id)));
            }
            else
            {
                CommandState state = null;

                using (var context = new IAContext())
                {
                    long guildId = id.ToDbLong();
                    state = await context.CommandStates.FindAsync(Name, guildId);
                }

                bool currentState = state?.State ?? DefaultEnabled;
                await client.UpsertAsync(GetCacheKey(id), currentState);

                return(currentState);
            }
        }
Beispiel #6
0
        public async Task <bool> IsEnabled(ICacheClient cache, ulong id)
        {
            if (await cache.ExistsAsync(GetCacheKey(id)))
            {
                return(await cache.GetAsync <bool>(GetCacheKey(id)));
            }
            else
            {
                ModuleState state = null;

                using (var context = new IAContext())
                {
                    long guildId = id.ToDbLong();
                    state = await context.ModuleStates.FindAsync(SqlName, guildId);
                }

                if (state == null)
                {
                    await cache.UpsertAsync(GetCacheKey(id), Enabled);

                    return(Enabled);
                }

                await cache.UpsertAsync(GetCacheKey(id), state.State);

                return(state.State);
            }
        }
Beispiel #7
0
        private async Task <T> CacheLoadItem <T>(Func <Task <T> > loader, string cacheKey)
        {
            if (await CacheClient.ExistsAsync(cacheKey).ConfigureAwait(false))
            {
                Logger.LogTrace("Cache Key exists {CacheKey}", cacheKey);

                var l = await CacheClient.GetAsync <T>(cacheKey).ConfigureAwait(false);

                if (l.HasValue)
                {
                    Logger.LogTrace("Return result from Cache with {CacheKey}", cacheKey);

                    return(l.Value);
                }
            }

            Logger.LogTrace("No Cache Result {CacheKey}", cacheKey);

            var ret = await loader().ConfigureAwait(false);

            if (ret != null)
            {
                Logger.LogTrace("Loaded Result. Set to Cache {CacheKey}", cacheKey);
                await CacheClient.SetAsync(cacheKey, ret, DateTime.UtcNow.AddMinutes(CacheOptions.CacheMinutes)).ConfigureAwait(false);
            }

            return(ret);
        }
Beispiel #8
0
        public void UpdateSession(PlayerSessionDto dto)
        {
            if (!_cache.ExistsAsync(ToKey(dto)).GetAwaiter().GetResult())
            {
                return;
            }

            _cache.ReplaceAsync(ToKey(dto), dto).GetAwaiter().GetResult();
        }
Beispiel #9
0
 /// <summary>Gets the grant.</summary>
 /// <param name="key">The key.</param>
 /// <returns></returns>
 public Task <PersistedGrant> GetAsync(string key)
 {
     if (_cacheClient.ExistsAsync(key).Result)
     {
         var ss = _cacheClient.GetAsync <PersistedGrant>(key).Result;
         return(Task.FromResult <PersistedGrant>(_cacheClient.GetAsync <PersistedGrant>(key).Result.Value));
     }
     return(Task.FromResult <PersistedGrant>((PersistedGrant)null));
 }
Beispiel #10
0
        async Task Test <T>(ICacheClient client, T value, T value2)
        {
            string itemKey = "test";

            await client.UpsertAsync(itemKey, value);

            await client.ExistsAsync(itemKey);

            T x = await client.GetAsync <T>(itemKey);

            await client.RemoveAsync(itemKey);
        }
Beispiel #11
0
        public async Task <StartSessionResponse> Start(StartSessionRequest request)
        {
            var source = new CancellationTokenSource();
            var result = SessionRegistryResult.Ok;

            source.CancelAfter(SessionLockTimeoutDuration);

            var session = request.Session;
            var @lock   = await _locker.AcquireAsync(session.Account.ToString(), cancellationToken : source.Token);

            if (@lock != null)
            {
                var timeout = DateTime.UtcNow.Add(SessionTimeoutDuration);

                if (await _sessionAccountCache.ExistsAsync(request.Session.Account.ToString()))
                {
                    result = SessionRegistryResult.FailedAlreadyStarted;
                }

                if (result == SessionRegistryResult.Ok)
                {
                    await _sessionAccountCache.SetAsync(session.Account.ToString(), session, timeout);

                    if (session.Character.HasValue)
                    {
                        await _sessionCharacterCache.SetAsync(session.Character.Value.ToString(), session, timeout);
                    }
                }

                await @lock.ReleaseAsync();
            }
            else
            {
                result = SessionRegistryResult.FailedTimeout;
            }

            return(new StartSessionResponse {
                Result = result
            });
        }
Beispiel #12
0
        public async Task <string> GetForGuildAsync(IUnitOfWork db, ICacheClient cache, ulong id)
        {
            if (await cache.ExistsAsync(GetCacheKey(id)))
            {
                return(await cache.GetAsync <string>(GetCacheKey(id)));
            }

            string dbPrefix = await LoadFromDatabaseAsync(db, id);

            await cache.UpsertAsync(GetCacheKey(id), dbPrefix);

            return(dbPrefix);
        }
Beispiel #13
0
        public async Task <string> GetForGuildAsync(ICacheClient cache, ulong id)
        {
            if (Changable)
            {
                if (await cache.ExistsAsync(GetCacheKey(id)))
                {
                    return(await cache.GetAsync <string>(GetCacheKey(id)));
                }
                string dbPrefix = await LoadFromDatabase(id);

                await cache.UpsertAsync(GetCacheKey(id), dbPrefix);

                return(dbPrefix);
            }
            return(DefaultValue);
        }
Beispiel #14
0
        public async Task <TEntry> Retrieve(int key)
        {
            if (!await _cache.ExistsAsync(key.ToString()) && _providers.ContainsKey(key))
            {
                var provider = _providers[key];
                var template = await provider.Provide();

                await _cache.SetAsync(key.ToString(), template);
            }

            var entry = await _cache.GetAsync <TEntry>(key.ToString());

            if (entry.HasValue)
            {
                await _cache.SetExpirationAsync(key.ToString(), _duration);

                return(entry.Value);
            }
            return(null);
        }
Beispiel #15
0
        public async Task <DiscordUserPacket> GetCurrentUserAsync()
        {
            string key = $"discord:user:self";

            if (await cache.ExistsAsync(key))
            {
                return(await cache.GetAsync <DiscordUserPacket>(key));
            }

            RestResponse <DiscordUserPacket> rc = await RestClient
                                                  .GetAsync <DiscordUserPacket>($"/users/@me");

            await cache.AddAsync(key, rc.Data);

            return(rc.Data);
        }
Beispiel #16
0
 public Task <bool> ExistsAsync(string key) => client.ExistsAsync(keyPrefix + key);
Beispiel #17
0
        public async Task OnMessage(WebhookResponse response)
        {
            using (var context = new MikiContext())
            {
                DblVoteObject voteObject = response.data.ToObject <DblVoteObject>();

                if (voteObject.Type == "upvote")
                {
                    User u = await context.Users.FindAsync(voteObject.UserId);

                    if (!await redisClient.ExistsAsync($"dbl:vote:{voteObject.UserId}"))
                    {
                        u.DblVotes++;
                        await redisClient.AddAsync($"dbl:vote:{voteObject.UserId}", 1, new TimeSpan(1, 0, 0, 0));

                        int addedCurrency = 100 * ((await u.IsDonatorAsync(context)) ? 2 : 1);

                        u.Currency += addedCurrency;

                        DogStatsd.Increment("votes.dbl");

                        Achievement achievement = await context.Achievements.FindAsync("voter", u.Id);

                        bool unlockedAchievement = false;

                        switch (u.DblVotes)
                        {
                        case 1:
                        {
                            achievement = new Achievement()
                            {
                                Name       = "voter",
                                Rank       = 0,
                                UnlockedAt = DateTime.Now,
                                Id         = u.Id
                            };
                            unlockedAchievement = true;
                        }
                        break;

                        case 25:
                        {
                            achievement.Rank    = 1;
                            unlockedAchievement = true;
                        }
                        break;

                        case 200:
                        {
                            achievement.Rank    = 2;
                            unlockedAchievement = true;
                        }
                        break;
                        }

                        await context.SaveChangesAsync();
                    }
                }
            }

            var client = new RestClient(ApiUrl)
                         .SetAuthorization(ApiAuthorization);

            await client.PostAsync("api/users/121919449996460033/messages", "{\"content\": \"yo.\"}");
        }
Beispiel #18
0
 public Task <bool> ExistsAsync <T>(string key)
 {
     return(_clientExt.ExistsAsync(RedisUtils.KeyBuilder <T>(key)));
 }
Beispiel #19
0
        public async Task <bool> IsLockedAsync(string resource)
        {
            var result = await Run.WithRetriesAsync(() => _cacheClient.ExistsAsync(resource), logger : _logger).AnyContext();

            return(result);
        }
Beispiel #20
0
 protected virtual async Task <bool> Exists(string key)
 {
     return(await _cache.ExistsAsync(key).ConfigureAwait(false));
 }
Beispiel #21
0
        async Task Test <T>(ICacheClient client, T value, T value2)
        {
            string itemKey = "test";

            await client.UpsertAsync(itemKey, value);

            Assert.True(await client.ExistsAsync(itemKey));

            T i = await client.GetAsync <T>(itemKey);

            Assert.Equal(value, i);

            await client.RemoveAsync(itemKey);

            if (client is IExtendedCacheClient ex)
            {
                string hashKey = "test:hash";

                Assert.False(await client.ExistsAsync(hashKey));
                Assert.False(await ex.HashExistsAsync(hashKey, itemKey));

                Assert.DoesNotContain(await ex.HashKeysAsync(hashKey), x => x == itemKey);
                Assert.DoesNotContain(await ex.HashValuesAsync <T>(hashKey), x => x.Equals(value));
                Assert.DoesNotContain(await ex.HashGetAllAsync <T>(hashKey), x => x.Key == itemKey && x.Value.Equals(value));

                Assert.NotEqual(value, await ex.HashGetAsync <T>(hashKey, itemKey));
                Assert.NotEqual(1, await ex.HashLengthAsync(hashKey));

                await ex.HashUpsertAsync(hashKey, itemKey, value);

                Assert.True(await client.ExistsAsync(hashKey));
                Assert.True(await ex.HashExistsAsync(hashKey, itemKey));

                Assert.Contains(await ex.HashKeysAsync(hashKey), x => x == itemKey);
                Assert.Contains(await ex.HashValuesAsync <T>(hashKey), x => x.Equals(value));
                Assert.Contains(await ex.HashGetAllAsync <T>(hashKey), x => x.Key == itemKey && x.Value.Equals(value));

                Assert.Equal(value, await ex.HashGetAsync <T>(hashKey, itemKey));
                Assert.Equal(1, await ex.HashLengthAsync(hashKey));

                await ex.HashUpsertAsync(hashKey, itemKey, value2);

                Assert.True(await client.ExistsAsync(hashKey));
                Assert.True(await ex.HashExistsAsync(hashKey, itemKey));

                var keys = await ex.HashKeysAsync(hashKey);

                Assert.Contains(keys, x => x == itemKey);

                var values = await ex.HashValuesAsync <T>(hashKey);

                Assert.Contains(values, x => x.Equals(value2));

                Assert.Contains(await ex.HashGetAllAsync <T>(hashKey), x => x.Key == itemKey && x.Value.Equals(value2));

                Assert.Equal(value2, await ex.HashGetAsync <T>(hashKey, itemKey));
                Assert.Equal(1, await ex.HashLengthAsync(hashKey));

                await ex.HashDeleteAsync(hashKey, itemKey);

                Assert.Equal(default, await ex.HashGetAsync <T>(hashKey, itemKey));