Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions AsyncGenerator.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,33 @@
projects:
- filePath: CoreDistributedCache\NHibernate.Caches.CoreDistributedCache\NHibernate.Caches.CoreDistributedCache.csproj
targetFramework: net461
concurrentRun: true
applyChanges: true
analyzation:
methodConversion:
- conversion: Ignore
hasAttributeName: ObsoleteAttribute
callForwarding: true
cancellationTokens:
guards: true
methodParameter:
- anyInterfaceRule: PubliclyExposedType
parameter: Optional
- parameter: Optional
rule: PubliclyExposedType
- parameter: Required
scanMethodBody: true
scanForMissingAsyncMembers:
- all: true
transformation:
configureAwaitArgument: false
localFunctions: true
asyncLock:
type: NHibernate.Util.AsyncLock
methodName: LockAsync
registerPlugin:
- type: AsyncGenerator.Core.Plugins.EmptyRegionRemover
assemblyName: AsyncGenerator.Core
- filePath: CoreMemoryCache\NHibernate.Caches.CoreMemoryCache\NHibernate.Caches.CoreMemoryCache.csproj
targetFramework: net461
concurrentRun: true
Expand Down Expand Up @@ -293,6 +322,47 @@
registerPlugin:
- type: AsyncGenerator.Core.Plugins.NUnitAsyncCounterpartsFinder
assemblyName: AsyncGenerator.Core
- filePath: CoreDistributedCache\NHibernate.Caches.CoreDistributedCache.Tests\NHibernate.Caches.CoreDistributedCache.Tests.csproj
targetFramework: net461
concurrentRun: true
applyChanges: true
analyzation:
methodConversion:
- conversion: Ignore
hasAttributeName: OneTimeSetUpAttribute
- conversion: Ignore
hasAttributeName: OneTimeTearDownAttribute
- conversion: Ignore
hasAttributeName: SetUpAttribute
- conversion: Ignore
hasAttributeName: TearDownAttribute
- conversion: Smart
hasAttributeName: TestAttribute
- conversion: Smart
hasAttributeName: TheoryAttribute
preserveReturnType:
- hasAttributeName: TestAttribute
- hasAttributeName: TheoryAttribute
typeConversion:
- conversion: Ignore
hasAttributeName: IgnoreAttribute
- conversion: Partial
hasAttributeName: TestFixtureAttribute
- conversion: Partial
anyBaseTypeRule: HasTestFixtureAttribute
ignoreSearchForMethodReferences:
- hasAttributeName: TheoryAttribute
- hasAttributeName: TestAttribute
cancellationTokens:
withoutCancellationToken:
- hasAttributeName: TestAttribute
- hasAttributeName: TheoryAttribute
scanMethodBody: true
scanForMissingAsyncMembers:
- all: true
registerPlugin:
- type: AsyncGenerator.Core.Plugins.NUnitAsyncCounterpartsFinder
assemblyName: AsyncGenerator.Core
- filePath: CoreMemoryCache\NHibernate.Caches.CoreMemoryCache.Tests\NHibernate.Caches.CoreMemoryCache.Tests.csproj
targetFramework: net461
concurrentRun: true
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
using System;
using System.Reflection;

[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(false)]
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace NHibernate.Caches.CoreDistributedCache.Memcached
{
/// <summary>
/// A Memcached distributed cache factory.
/// </summary>
public class MemcachedFactory : IDistributedCacheFactory
{
private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(MemcachedFactory));
private const string _configuration = "configuration";

private readonly IDistributedCache _cache;

/// <summary>
/// Constructor with configuration properties. It supports <c>configuration</c>, which has to be a JSON string
/// structured like the value part of the <c>"enyimMemcached"</c> property in an appsettings.json file.
/// </summary>
/// <param name="properties">The configurations properties.</param>
public MemcachedFactory(IDictionary<string, string> properties) : this()
{
MemcachedClientOptions options;
if (properties != null && properties.TryGetValue(_configuration, out var configuration) && !string.IsNullOrWhiteSpace(configuration))
{
options = JsonConvert.DeserializeObject<MemcachedClientOptions>(configuration);
}
else
{
Log.Warn("No {0} property provided", _configuration);
options = new MemcachedClientOptions();
}

var loggerFactory = new LoggerFactory();

_cache = new MemcachedClient(loggerFactory, new MemcachedClientConfiguration(loggerFactory, options));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a bit messy to integrate a library meant to be used with the .Net Core default dependency injection system with NHibernate factories/configuration logic.

EnyimMemcachedCore was the worst case, due to its dependency on a logger factory (I have provided it through a wrapping of the NHibernate one) and its structured configuration (thus the JSON trick I have choosen for it).

Maybe should each factory also expose directly a constructor with the cache dependencies (at least IMemcachedClientConfiguration and maybe ILoggerFactory for this case)for users who would set the factory programmatically.

}

private MemcachedFactory()
{
Constraints = new CacheConstraints
{
MaxKeySize = 250,
KeySanitizer = SanitizeKey
};
}

// According to https://groups.google.com/forum/#!topic/memcached/Tz1RE0FUbNA,
// memcached key can't contain space, newline, return, tab, vertical tab or form feed.
// Since keys contains entity identifiers which may be anything, purging them all.
private static readonly char[] ForbiddenChar = new [] { ' ', '\n', '\r', '\t', '\v', '\f' };

private static string SanitizeKey(string key)
{
foreach (var forbidden in ForbiddenChar)
{
key = key.Replace(forbidden, '-');
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have checked two other implementations: Regex and StringBuilder. They were no match in execution time, so keeping this basic Replace one.

For reference, here is how I have checked:

[Test]
public void PerfTest()
{
	var keys = new[]
	{
		"abcdefghijklmnopkrstuvwxyz",
		"abcde\fghijklm\nopk\r \tu\vwxyz",
		"abcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyz" +
		"abcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyz",
		"abcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyz" +
		"abcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyz"
	};

	var sw = new Stopwatch();
	Regex purgeForbiddenChar = null;
	HashSet<char> forbiddenCharSet = null;
	char[] forbiddenChar = null;

	var algos = new[]
	{
		new Tuple<string, System.Action, Func<string, string>>("Regex",
			() => purgeForbiddenChar = new Regex("[ \n\r\t\v\f]", RegexOptions.Compiled),
			s => purgeForbiddenChar.Replace(s, "-")),
		new Tuple<string, System.Action, Func<string, string>>("Builder",
			() => forbiddenCharSet = new HashSet<char> { ' ', '\n', '\r', '\t', '\v', '\f' },
			s =>
			{
				var sanitizedKey = new StringBuilder();
				foreach (var c in s)
				{
					sanitizedKey.Append(forbiddenCharSet.Contains(c) ? '-' : c);
				}
				return sanitizedKey.ToString();
			}),
		new Tuple<string, System.Action, Func<string, string>>("Replace",
			() => forbiddenChar = new[] { '\n', ' ', '\r', '\t', '\v', '\f' },
			s =>
			{
				foreach (var forbidden in forbiddenChar)
				{
					s = s.Replace(forbidden, '-');
				}
				return s;
			})
	};

	foreach (var algo in algos)
	{
		sw.Restart();
		algo.Item2();
		foreach (var k in keys)
		{
			Console.WriteLine(algo.Item3(k));
		}
		Console.WriteLine($"{sw.Elapsed} for {algo.Item1} warmup");
		foreach (var k in keys)
		{
			sw.Restart();
			for (var i = 0; i < 1000; i++)
			{
				algo.Item3(k + i);
			}
			Console.WriteLine($"{sw.Elapsed} for {algo.Item1} key {k}");
		}
	}
}

return key;
}

/// <inheritdoc />
public CacheConstraints Constraints { get; }

/// <inheritdoc />
[CLSCompliant(false)]
public IDistributedCache BuildCache()
{
return _cache;
}

private class LoggerFactory : Microsoft.Extensions.Logging.ILoggerFactory
{
public void Dispose()
{
}

public ILogger CreateLogger(string categoryName)
{
return new LoggerWrapper(NHibernateLogger.For(categoryName));
}

public void AddProvider(ILoggerProvider provider)
{
}
}

private class LoggerWrapper : ILogger
{
private readonly INHibernateLogger _logger;

public LoggerWrapper(INHibernateLogger logger)
{
_logger = logger;
}

void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
return;

if (formatter == null)
throw new ArgumentNullException(nameof(formatter));

_logger.Log(
TranslateLevel(logLevel),
new NHibernateLogValues("EventId {0}: {1}", new object[] { eventId, formatter(state, exception) }),
// Avoid double logging of exception by not providing it to the logger, but only to the formatter.
null);
}

public bool IsEnabled(LogLevel logLevel)
=> _logger.IsEnabled(TranslateLevel(logLevel));

public IDisposable BeginScope<TState>(TState state)
=> NoopScope.Instance;

private NHibernateLogLevel TranslateLevel(LogLevel level)
{
switch (level)
{
case LogLevel.None:
return NHibernateLogLevel.None;
case LogLevel.Trace:
return NHibernateLogLevel.Trace;
case LogLevel.Debug:
return NHibernateLogLevel.Debug;
case LogLevel.Information:
return NHibernateLogLevel.Info;
case LogLevel.Warning:
return NHibernateLogLevel.Warn;
case LogLevel.Error:
return NHibernateLogLevel.Error;
case LogLevel.Critical:
return NHibernateLogLevel.Fatal;
}

return NHibernateLogLevel.Trace;
}

private class NoopScope : IDisposable
{
public static readonly NoopScope Instance = new NoopScope();

public void Dispose()
{
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../../NHibernate.Caches.props" />
<PropertyGroup>
<Product>NHibernate.Caches.CoreDistributedCache.Memcached</Product>
<Title>NHibernate.Caches.CoreDistributedCache.Memcached</Title>
<Description>Memcached cache provider for NHibernate using .Net Core IDistributedCache (EnyimMemcachedCore).</Description>
<!-- Targeting net461 explicitly in order to avoid https://github.com/dotnet/standard/issues/506 for net461 consumers-->
<TargetFrameworks>net461;netstandard2.0</TargetFrameworks>
<SignAssembly>False</SignAssembly>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReleaseNotes>* New feature
* #28 - Add a .Net Core DistributedCache</PackageReleaseNotes>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net461'">
<DefineConstants>NETFX;$(DefineConstants)</DefineConstants>
</PropertyGroup>
<ItemGroup>
<None Include="..\..\NHibernate.Caches.snk" Link="NHibernate.snk" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NHibernate.Caches.CoreDistributedCache\NHibernate.Caches.CoreDistributedCache.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="../../readme.md">
<PackagePath>./NHibernate.Caches.readme.md</PackagePath>
</Content>
<Content Include="../../LICENSE.txt">
<PackagePath>./NHibernate.Caches.license.txt</PackagePath>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="EnyimMemcachedCore" Version="2.1.0" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
using System;
using System.Reflection;

[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(false)]
Loading