Skip to content

Commit

Permalink
https://github.com/valdisiljuconoks/localization-provider-opti/issues…
Browse files Browse the repository at this point in the history
…/220
  • Loading branch information
Valdis Iljuconoks committed Jun 5, 2024
1 parent 4dc0b50 commit 0c614d6
Show file tree
Hide file tree
Showing 8 changed files with 73 additions and 63 deletions.
18 changes: 0 additions & 18 deletions Tests/DbLocalizationProvider.Tests/UnitTestCache.cs

This file was deleted.

36 changes: 27 additions & 9 deletions src/DbLocalizationProvider/Cache/BaseCacheManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@

namespace DbLocalizationProvider.Cache;

internal class BaseCacheManager(ICacheManager inner) : ICacheManager
internal class BaseCacheManager(ICache inner) : ICacheManager
{
private readonly ConcurrentDictionary<string, object> _knownResourceKeys = new(StringComparer.InvariantCultureIgnoreCase);
private readonly ConcurrentDictionary<string, bool> _entries = new();
internal Func<IServiceProvider, ICache>? _implementationFactory;
internal ICache _inner = inner;

internal int KnownKeyCount => _knownResourceKeys.Count;

Expand All @@ -19,7 +22,11 @@ public void Insert(string key, object value, bool insertIntoKnownResourceKeys)
{
VerifyInstance();

inner.Insert(key.ToLower(), value, insertIntoKnownResourceKeys);
var k = key.ToLower();
_inner.Insert(k, value, insertIntoKnownResourceKeys);
_entries.TryRemove(k, out _);
_entries.TryAdd(k, true);

var resourceKey = CacheKeyHelper.GetResourceKeyFromCacheKey(key);

if (insertIntoKnownResourceKeys)
Expand All @@ -33,23 +40,29 @@ public void Insert(string key, object value, bool insertIntoKnownResourceKeys)
public object Get(string key)
{
VerifyInstance();
return inner.Get(key.ToLower());
return _inner.Get(key.ToLower());
}

public void Remove(string key)
{
VerifyInstance();
inner.Remove(key.ToLower());

var k = key.ToLower();
_inner.Remove(k);
_entries.TryRemove(k, out _);

OnRemove?.Invoke(new CacheEventArgs(CacheOperation.Remove, key, CacheKeyHelper.GetResourceKeyFromCacheKey(key)));
}

public IEnumerable<string> Keys => _entries.Keys;

public event CacheEventHandler? OnInsert;
public event CacheEventHandler? OnRemove;

public void SetInnerManager(ICacheManager implementation)
internal void SetInnerManager(ICache implementation)
{
inner = implementation ?? throw new ArgumentNullException(nameof(implementation));
_inner = implementation ?? throw new ArgumentNullException(nameof(implementation));
_implementationFactory = null;
}

internal bool IsKeyKnown(string key)
Expand All @@ -64,20 +77,25 @@ internal void StoreKnownKey(string key)

internal void SetKnownKeysStored()
{
inner.Insert(CacheKeyHelper.BuildKey("KnownKeysSynched"), true, false);
_inner.Insert(CacheKeyHelper.BuildKey("KnownKeysSynced"), true, false);
}

internal bool AreKnownKeysStored()
{
return inner.Get(CacheKeyHelper.BuildKey("KnownKeysSynched")) as bool? ?? false;
return _inner.Get(CacheKeyHelper.BuildKey("KnownKeysSynced")) as bool? ?? false;
}

private void VerifyInstance()
{
if (inner == null)
if (_inner == null)
{
throw new InvalidOperationException(
"Cache implementation is not set. Use `ConfigurationContext.CacheManager` setter.");
}
}

public void SetInnerManager(Func<IServiceProvider, ICache>? implementationFactory)
{
_implementationFactory = implementationFactory;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ namespace DbLocalizationProvider.Cache;
/// <summary>
/// Cache implementation for cases when you have enough memory.
/// </summary>
/// <seealso cref="DbLocalizationProvider.Cache.ICacheManager" />
public class InMemoryCache : ICacheManager
public class DictionaryBasedCache : ICache
{
private static readonly ConcurrentDictionary<string, object> _cache = new();

Expand All @@ -21,7 +20,6 @@ public class InMemoryCache : ICacheManager
/// <param name="insertIntoKnownResourceKeys">This is pretty internal stuff and should be ignored by cache implementers.</param>
public void Insert(string key, object value, bool insertIntoKnownResourceKeys)
{
_cache.TryRemove(key, out _);
_cache.TryAdd(key, value);
}

Expand All @@ -45,14 +43,4 @@ public void Remove(string key)
{
_cache.TryRemove(key, out _);
}

/// <summary>
/// Event raise is taken care by <see cref="BaseCacheManager" />.
/// </summary>
public event CacheEventHandler OnInsert;

/// <summary>
/// Event raise is taken care by <see cref="BaseCacheManager" />.
/// </summary>
public event CacheEventHandler OnRemove;
}
31 changes: 31 additions & 0 deletions src/DbLocalizationProvider/Cache/ICache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) Valdis Iljuconoks. All rights reserved.
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information

namespace DbLocalizationProvider.Cache;

/// <summary>
/// Interface for implementing cache.
/// </summary>
public interface ICache
{
/// <summary>
/// You should add given value to the cache under given key.
/// </summary>
/// <param name="key">Key identifier of the cached item</param>
/// <param name="value">Actual value fo the cached item</param>
/// <param name="insertIntoKnownResourceKeys">This is pretty internal stuff and should be ignored by cache implementers.</param>
void Insert(string key, object value, bool insertIntoKnownResourceKeys);

/// <summary>
/// You should implement this method to get cached item back from the underlying storage
/// </summary>
/// <param name="key">Key identifier of the cached item</param>
/// <returns>Actual value fo the cached item. Take care of casting back to proper type.</returns>
object Get(string key);

/// <summary>
/// If you want to remove the cached item from the storage - this is the method to implement then.
/// </summary>
/// <param name="key">Key identifier of the cached item</param>
void Remove(string key);
}
7 changes: 7 additions & 0 deletions src/DbLocalizationProvider/Cache/ICacheManager.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Valdis Iljuconoks. All rights reserved.
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information

using System.Collections.Generic;

namespace DbLocalizationProvider.Cache;

/// <summary>
Expand Down Expand Up @@ -29,6 +31,11 @@ public interface ICacheManager
/// <param name="key">Key identifier of the cached item</param>
void Remove(string key);

/// <summary>
/// List of known keys in the cache.
/// </summary>
IEnumerable<string> Keys { get; }

/// <summary>
/// Event raise is taken care by <see cref="BaseCacheManager" />.
/// </summary>
Expand Down
16 changes: 2 additions & 14 deletions src/DbLocalizationProvider/ConfigurationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class ConfigurationContext
/// </summary>
public const string CultureForTranslationsFromCode = "";

internal BaseCacheManager _baseCacheManager = new(new InMemoryCache());
internal BaseCacheManager _baseCacheManager = new(new DictionaryBasedCache());

internal FallbackLanguagesCollection _fallbackCollection = new();

Expand Down Expand Up @@ -133,18 +133,6 @@ public ConfigurationContext(IServiceCollection services) : this()
public ICacheManager CacheManager
{
get => _baseCacheManager;
set
{
if (value != null)
{
_baseCacheManager.SetInnerManager(value);
}
}
}

private void CopyCacheManager(BaseCacheManager cacheManager)
{
_baseCacheManager = cacheManager;
}

/// <summary>
Expand Down Expand Up @@ -235,7 +223,7 @@ internal void CopyFrom(ConfigurationContext ctx)
throw new ArgumentNullException(nameof(ctx));
}

CopyCacheManager(ctx._baseCacheManager);
_baseCacheManager = ctx._baseCacheManager;

EnableLocalization = ctx.EnableLocalization;
EnableLegacyMode = ctx.EnableLegacyMode;
Expand Down
2 changes: 1 addition & 1 deletion src/DbLocalizationProvider/Queries/GetTranslation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public string Execute(Query query)

if (_configurationContext.Value.DiagnosticsEnabled)
{
_logger.Debug($"Executing query for resource key `{key}` (lang: `{query.Language.Name})..");
_logger.Debug($"Executing query for resource key `{key}` (lang: `{query.Language.Name}`)..");
}

var localizationResource = GetCachedResourceOrReadFromStorage(query);
Expand Down
12 changes: 4 additions & 8 deletions src/DbLocalizationProvider/TypeFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,12 @@ public TypeFactory AddTransient<TService, TImplementation>()
/// <returns>Type of the handler; otherwise of course <c>null</c> if not found.</returns>
public Type GetHandlerType<T>()
{
if (_mappings.ContainsKey(typeof(T)))
if (!_mappings.ContainsKey(typeof(T)))
{
if (_mappings.TryGetValue(typeof(T), out var info))
{
return info.Item1;
}
return null;
}

return null;
return _mappings.TryGetValue(typeof(T), out var info) ? info.Item1 : null;
}

internal QueryHandlerWrapper<TResult> GetQueryHandler<TResult>(IQuery<TResult> query)
Expand Down Expand Up @@ -185,12 +182,11 @@ internal object GetHandler(Type queryType)

var instance = factory.Item2(queryType);

if (!_decoratorMappings.ContainsKey(queryType))
if (!_decoratorMappings.TryGetValue(queryType, out var decoratorType))
{
return instance;
}

var decoratorType = _decoratorMappings[queryType];
var constructors = decoratorType
.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
.OrderByDescending(c => c.GetParameters().Length)
Expand Down

0 comments on commit 0c614d6

Please sign in to comment.