From 6fda7f00ad8aad2d5ab86abab8f5dc6c69f72fca Mon Sep 17 00:00:00 2001 From: Jeff Ward Date: Wed, 11 Jan 2023 10:48:43 -0500 Subject: [PATCH 1/2] implementing async versions --- Revoke.NET.Akavache/AkavacheBlackList.cs | 15 ++- .../Revoke.NET.Akavache.csproj | 4 +- Revoke.NET.Akavache/RevokeService.cs | 4 +- .../Revoke.NET.AspNetCore.csproj | 1 - Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs | 26 +++- Revoke.NET.AspNetCore/RevokeService.cs | 74 ++++++----- .../EasyCachingBlackList.cs | 12 +- .../Revoke.NET.EasyCaching.csproj | 6 +- Revoke.NET.EasyCaching/RevokeService.cs | 21 ++- Revoke.NET.MinimalAPIExample/Program.cs | 10 +- .../Revoke.NET.MinimalAPIExample.csproj | 3 - Revoke.NET.MongoDB/MongoBlackList.cs | 32 +++-- Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj | 2 - Revoke.NET.MongoDB/RevokeService.cs | 9 +- Revoke.NET.Redis/RedisBlackList.cs | 34 +++-- Revoke.NET.Redis/Revoke.NET.Redis.csproj | 3 - Revoke.NET.Redis/RevokeService.cs | 4 +- Revoke.NET/IBlackList.cs | 59 ++++++++- Revoke.NET/Internals/RevokeGuardExtensions.cs | 27 ++++ Revoke.NET/MemoryBlackList.cs | 121 ++++++++++++++++- Revoke.NET/MemoryCacheBlackList.cs | 123 ++++++++++++++++-- Revoke.NET/Revoke.NET.csproj | 1 - Revoke.NET/RevokeService.cs | 19 ++- Test/Program.cs | 7 +- Test/Test.csproj | 3 - 25 files changed, 495 insertions(+), 125 deletions(-) create mode 100644 Revoke.NET/Internals/RevokeGuardExtensions.cs diff --git a/Revoke.NET.Akavache/AkavacheBlackList.cs b/Revoke.NET.Akavache/AkavacheBlackList.cs index d1c0ba2..bc3212b 100644 --- a/Revoke.NET.Akavache/AkavacheBlackList.cs +++ b/Revoke.NET.Akavache/AkavacheBlackList.cs @@ -39,7 +39,7 @@ public async Task IsRevoked(string key) try { await this._blackList.Vacuum(); - var exist = await this._blackList.Get(key); + byte[] exist = await this._blackList.Get(key); return exist.Length > 0; } @@ -63,7 +63,9 @@ public async Task Revoke(string key) } } - public async Task Revoke(string key, TimeSpan expireAfter) + public async Task Revoke( + string key, + TimeSpan expireAfter) { try { @@ -77,7 +79,9 @@ public async Task Revoke(string key, TimeSpan expireAfter) } } - public async Task Revoke(string key, DateTime expireOn) + public async Task Revoke( + string key, + DateTime expireOn) { try { @@ -91,7 +95,10 @@ public async Task Revoke(string key, DateTime expireOn) } } - public static async Task CreateStoreAsync(string cacheName, IBlobCache blobCache, TimeSpan? defaultTtl = null) + public static async Task CreateStoreAsync( + string cacheName, + IBlobCache blobCache, + TimeSpan? defaultTtl = null) { _defaultTtl = defaultTtl; Registrations.Start(cacheName); diff --git a/Revoke.NET.Akavache/Revoke.NET.Akavache.csproj b/Revoke.NET.Akavache/Revoke.NET.Akavache.csproj index 1de1484..fd26d63 100644 --- a/Revoke.NET.Akavache/Revoke.NET.Akavache.csproj +++ b/Revoke.NET.Akavache/Revoke.NET.Akavache.csproj @@ -1,7 +1,6 @@  - - netstandard2.0 + netstandard2.0 10.0 revoke.net.png readme.md @@ -22,7 +21,6 @@ False True - diff --git a/Revoke.NET.Akavache/RevokeService.cs b/Revoke.NET.Akavache/RevokeService.cs index 309d991..c3984ab 100644 --- a/Revoke.NET.Akavache/RevokeService.cs +++ b/Revoke.NET.Akavache/RevokeService.cs @@ -22,7 +22,9 @@ public static IServiceCollection AddRevokeAkavacheInMemoryStore(this IServiceCol .GetResult()); } - public static IServiceCollection AddRevokeAkavacheStore(this IServiceCollection services, Func configBlobCache) + public static IServiceCollection AddRevokeAkavacheStore( + this IServiceCollection services, + Func configBlobCache) { return services.AddSingleton( provider => AkavacheBlackList.CreateStoreAsync("RevokeStore", configBlobCache(provider)) diff --git a/Revoke.NET.AspNetCore/Revoke.NET.AspNetCore.csproj b/Revoke.NET.AspNetCore/Revoke.NET.AspNetCore.csproj index 687fee1..e99fcdb 100644 --- a/Revoke.NET.AspNetCore/Revoke.NET.AspNetCore.csproj +++ b/Revoke.NET.AspNetCore/Revoke.NET.AspNetCore.csproj @@ -1,5 +1,4 @@ - netstandard2.1 10.0 diff --git a/Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs b/Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs index 7713f0d..f5c6d51 100644 --- a/Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs +++ b/Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs @@ -16,21 +16,28 @@ public class RevokeHttpMiddleware : IMiddleware private readonly Func>? _responseFunc; #nullable disable - public RevokeHttpMiddleware(IBlackList store, ILogger logger, Func selector) + public RevokeHttpMiddleware( + IBlackList store, + ILogger logger, + Func selector) { this._store = store; this._logger = logger; this._selector = selector; } - public RevokeHttpMiddleware(IBlackList store, Func selector) + public RevokeHttpMiddleware( + IBlackList store, + Func selector) { this._store = store; this._selector = selector; } public RevokeHttpMiddleware( - IBlackList store, ILogger logger, Func selector, + IBlackList store, + ILogger logger, + Func selector, Func> responseFunc) { this._store = store; @@ -39,18 +46,23 @@ public RevokeHttpMiddleware( this._responseFunc = responseFunc; } - public RevokeHttpMiddleware(IBlackList store, Func selector, Func> responseFunc) + public RevokeHttpMiddleware( + IBlackList store, + Func selector, + Func> responseFunc) { this._store = store; this._selector = selector; this._responseFunc = responseFunc; } - public async Task InvokeAsync(HttpContext context, RequestDelegate next) + public async Task InvokeAsync( + HttpContext context, + RequestDelegate next) { try { - var revokeKey = this._selector(context); + string revokeKey = this._selector(context); if (revokeKey != null) { if (await this._store.IsRevoked(revokeKey)) @@ -78,7 +90,7 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next) } catch (Exception ex) { - this._logger?.LogError("{ErrorMessage}",ex.Message); + this._logger?.LogError("{ErrorMessage}", ex.Message); await next(context); } } diff --git a/Revoke.NET.AspNetCore/RevokeService.cs b/Revoke.NET.AspNetCore/RevokeService.cs index 98d5114..548b5fa 100644 --- a/Revoke.NET.AspNetCore/RevokeService.cs +++ b/Revoke.NET.AspNetCore/RevokeService.cs @@ -7,16 +7,19 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Primitives; public static class RevokeService { - public static IServiceCollection AddHttpContextRevokeMiddleware(this IServiceCollection services, Func selector) + public static IServiceCollection AddHttpContextRevokeMiddleware( + this IServiceCollection services, + Func selector) { return services.AddSingleton( provider => { - var store = provider.GetService(); - var logger = provider.GetService>(); + IBlackList? store = provider.GetService(); + ILogger? logger = provider.GetService>(); return new RevokeHttpMiddleware(store, logger, selector); }); @@ -32,13 +35,16 @@ public static IServiceCollection AddHttpContextRevokeMiddleware(this IServiceCol /// /// custom response function /// - public static IServiceCollection AddHttpContextRevokeMiddleware(this IServiceCollection services, Func selector, Func> responseFunc) + public static IServiceCollection AddHttpContextRevokeMiddleware( + this IServiceCollection services, + Func selector, + Func> responseFunc) { return services.AddSingleton( provider => { - var store = provider.GetService(); - var logger = provider.GetService>(); + IBlackList? store = provider.GetService(); + ILogger? logger = provider.GetService>(); return new RevokeHttpMiddleware(store, logger, selector, responseFunc); }); @@ -51,12 +57,12 @@ public static IServiceCollection AddHttpContextRevokeMiddleware(this IServiceCol /// public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IServiceCollection services) { - var bearerTokenSelector = new Func( + Func? bearerTokenSelector = new Func( context => { - if (context.Request.Headers.TryGetValue("Authorization", out var authHeader)) + if (context.Request.Headers.TryGetValue("Authorization", out StringValues authHeader)) { - var jwtToken = AuthenticationHeaderValue.Parse(authHeader) + string? jwtToken = AuthenticationHeaderValue.Parse(authHeader) .Parameter; if (jwtToken != null) { @@ -70,8 +76,8 @@ public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IService return services.AddSingleton( provider => { - var store = provider.GetService(); - var logger = provider.GetService>(); + IBlackList? store = provider.GetService(); + ILogger? logger = provider.GetService>(); return new RevokeHttpMiddleware(store, logger, bearerTokenSelector); }); @@ -83,14 +89,16 @@ public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IService /// /// custom response function /// - public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IServiceCollection services, Func> responseFunc) + public static IServiceCollection AddJWTBearerTokenRevokeMiddleware( + this IServiceCollection services, + Func> responseFunc) { - var bearerTokenSelector = new Func( + Func? bearerTokenSelector = new Func( context => { - if (context.Request.Headers.TryGetValue("Authorization", out var authHeader)) + if (context.Request.Headers.TryGetValue("Authorization", out StringValues authHeader)) { - var jwtToken = AuthenticationHeaderValue.Parse(authHeader) + string? jwtToken = AuthenticationHeaderValue.Parse(authHeader) .Parameter; if (jwtToken != null) { @@ -104,8 +112,8 @@ public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IService return services.AddSingleton( provider => { - var store = provider.GetService(); - var logger = provider.GetService>(); + IBlackList? store = provider.GetService(); + ILogger? logger = provider.GetService>(); return new RevokeHttpMiddleware(store, logger, bearerTokenSelector, responseFunc); }); @@ -118,13 +126,13 @@ public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IService /// public static IServiceCollection AddIpRevokeMiddleware(this IServiceCollection services) { - var ipSelector = new Func(context => context.Request.Host.Host); + Func? ipSelector = new Func(context => context.Request.Host.Host); return services.AddSingleton( provider => { - var store = provider.GetService(); - var logger = provider.GetService>(); + IBlackList? store = provider.GetService(); + ILogger? logger = provider.GetService>(); return new RevokeHttpMiddleware(store, logger, ipSelector); }); @@ -136,15 +144,17 @@ public static IServiceCollection AddIpRevokeMiddleware(this IServiceCollection s /// /// custom response function /// - public static IServiceCollection AddIpRevokeMiddleware(this IServiceCollection services, Func> responseFunc) + public static IServiceCollection AddIpRevokeMiddleware( + this IServiceCollection services, + Func> responseFunc) { - var ipSelector = new Func(context => context.Request.Host.Host); + Func? ipSelector = new Func(context => context.Request.Host.Host); return services.AddSingleton( provider => { - var store = provider.GetService(); - var logger = provider.GetService>(); + IBlackList? store = provider.GetService(); + ILogger? logger = provider.GetService>(); return new RevokeHttpMiddleware(store, logger, ipSelector, responseFunc); }); @@ -157,13 +167,13 @@ public static IServiceCollection AddIpRevokeMiddleware(this IServiceCollection s /// public static IServiceCollection AddUserIdRevokeMiddleware(this IServiceCollection services) { - var ipSelector = new Func(context => context.Request.Host.Host); + Func? ipSelector = new Func(context => context.Request.Host.Host); return services.AddSingleton( provider => { - var store = provider.GetService(); - var logger = provider.GetService>(); + IBlackList? store = provider.GetService(); + ILogger? logger = provider.GetService>(); return new RevokeHttpMiddleware(store, logger, ipSelector); }); @@ -175,15 +185,17 @@ public static IServiceCollection AddUserIdRevokeMiddleware(this IServiceCollecti /// /// custom response function /// - public static IServiceCollection AddUserIdRevokeMiddleware(this IServiceCollection services, Func> responseFunc) + public static IServiceCollection AddUserIdRevokeMiddleware( + this IServiceCollection services, + Func> responseFunc) { - var ipSelector = new Func(context => context.Request.Host.Host); + Func? ipSelector = new Func(context => context.Request.Host.Host); return services.AddSingleton( provider => { - var store = provider.GetService(); - var logger = provider.GetService>(); + IBlackList? store = provider.GetService(); + ILogger? logger = provider.GetService>(); return new RevokeHttpMiddleware(store, logger, ipSelector, responseFunc); }); diff --git a/Revoke.NET.EasyCaching/EasyCachingBlackList.cs b/Revoke.NET.EasyCaching/EasyCachingBlackList.cs index 03c2cb2..bcb3193 100644 --- a/Revoke.NET.EasyCaching/EasyCachingBlackList.cs +++ b/Revoke.NET.EasyCaching/EasyCachingBlackList.cs @@ -9,13 +9,17 @@ internal class EasyCachingBlackList : IBlackList private readonly TimeSpan? _defaultTtl; private readonly IEasyCachingProvider _easyCaching; - public EasyCachingBlackList(IEasyCachingProvider easyCaching, TimeSpan? defaultTtl = null) + public EasyCachingBlackList( + IEasyCachingProvider easyCaching, + TimeSpan? defaultTtl = null) { this._defaultTtl = defaultTtl; this._easyCaching = easyCaching; } - public async Task Revoke(string key, TimeSpan expireAfter) + public async Task Revoke( + string key, + TimeSpan expireAfter) { try { @@ -29,7 +33,9 @@ public async Task Revoke(string key, TimeSpan expireAfter) } } - public async Task Revoke(string key, DateTime expireOn) + public async Task Revoke( + string key, + DateTime expireOn) { try { diff --git a/Revoke.NET.EasyCaching/Revoke.NET.EasyCaching.csproj b/Revoke.NET.EasyCaching/Revoke.NET.EasyCaching.csproj index 2c885a4..d3cbd85 100644 --- a/Revoke.NET.EasyCaching/Revoke.NET.EasyCaching.csproj +++ b/Revoke.NET.EasyCaching/Revoke.NET.EasyCaching.csproj @@ -1,5 +1,4 @@  - netstandard2.0 10.0 @@ -21,7 +20,6 @@ False True - @@ -31,9 +29,7 @@ - + - diff --git a/Revoke.NET.EasyCaching/RevokeService.cs b/Revoke.NET.EasyCaching/RevokeService.cs index 257948e..6a6847e 100644 --- a/Revoke.NET.EasyCaching/RevokeService.cs +++ b/Revoke.NET.EasyCaching/RevokeService.cs @@ -6,28 +6,37 @@ public static class RevokeService { - public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, IEasyCachingProvider easyCachingProvider, TimeSpan? defaultTtl = null) + public static IServiceCollection AddRevokeEasyCaching( + this IServiceCollection services, + IEasyCachingProvider easyCachingProvider, + TimeSpan? defaultTtl = null) { - return services.AddSingleton(_ => new EasyCachingBlackList(easyCachingProvider, defaultTtl)); + return services.AddSingleton( + _ => new EasyCachingBlackList(easyCachingProvider, defaultTtl)); } - public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, Func easyCachingConfig, TimeSpan? defaultTtl = null) + public static IServiceCollection AddRevokeEasyCaching( + this IServiceCollection services, + Func easyCachingConfig, + TimeSpan? defaultTtl = null) { return services.AddSingleton( provider => { - var factory = provider.GetService(); + IEasyCachingProviderFactory factory = provider.GetService(); return new EasyCachingBlackList(easyCachingConfig?.Invoke(factory), defaultTtl); }); } - public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, TimeSpan? defaultTtl = null) + public static IServiceCollection AddRevokeEasyCaching( + this IServiceCollection services, + TimeSpan? defaultTtl = null) { return services.AddSingleton( provider => { - var easyCachingProvider = provider.GetService(); + IEasyCachingProvider easyCachingProvider = provider.GetService(); return new EasyCachingBlackList(easyCachingProvider, defaultTtl); }); diff --git a/Revoke.NET.MinimalAPIExample/Program.cs b/Revoke.NET.MinimalAPIExample/Program.cs index 5c6cfed..3f5b0c8 100644 --- a/Revoke.NET.MinimalAPIExample/Program.cs +++ b/Revoke.NET.MinimalAPIExample/Program.cs @@ -3,12 +3,12 @@ using Revoke.NET; using Revoke.NET.AspNetCore; -var builder = WebApplication.CreateBuilder(args); +WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddRevokeInMemoryStore() // Register a Revoke Store .AddJWTBearerTokenRevokeMiddleware(); // Register a Revoke Middleware -var app = builder.Build(); +WebApplication app = builder.Build(); app.UseRevoke(); // Use Middleware before calling UseAuthorization() @@ -17,9 +17,11 @@ app.MapGet( "/logout", - async ([FromServices] IBlackList store, HttpRequest request) => + async ( + [FromServices] IBlackList store, + HttpRequest request) => { - var token = AuthenticationHeaderValue.Parse(request.Headers.Authorization) + string? token = AuthenticationHeaderValue.Parse(request.Headers.Authorization) .Parameter; await store.Revoke(token); diff --git a/Revoke.NET.MinimalAPIExample/Revoke.NET.MinimalAPIExample.csproj b/Revoke.NET.MinimalAPIExample/Revoke.NET.MinimalAPIExample.csproj index ca97af9..bca4370 100644 --- a/Revoke.NET.MinimalAPIExample/Revoke.NET.MinimalAPIExample.csproj +++ b/Revoke.NET.MinimalAPIExample/Revoke.NET.MinimalAPIExample.csproj @@ -1,11 +1,9 @@  - net6.0 enable enable - @@ -13,5 +11,4 @@ - diff --git a/Revoke.NET.MongoDB/MongoBlackList.cs b/Revoke.NET.MongoDB/MongoBlackList.cs index 9735aa8..c271fbd 100644 --- a/Revoke.NET.MongoDB/MongoBlackList.cs +++ b/Revoke.NET.MongoDB/MongoBlackList.cs @@ -8,7 +8,9 @@ public class MongoBlackListItem { - public MongoBlackListItem(string key, DateTime expireOn) + public MongoBlackListItem( + string key, + DateTime expireOn) { this.Key = key; this.ExpireOn = expireOn; @@ -30,7 +32,9 @@ private MongoBlackList(IMongoCollection blacklist) this._blacklist = blacklist; } - public async Task Revoke(string key, TimeSpan expireAfter) + public async Task Revoke( + string key, + TimeSpan expireAfter) { try { @@ -44,7 +48,9 @@ public async Task Revoke(string key, TimeSpan expireAfter) } } - public async Task Revoke(string key, DateTime expireOn) + public async Task Revoke( + string key, + DateTime expireOn) { try { @@ -76,7 +82,7 @@ public async Task Delete(string key) { try { - var delete = await this._blacklist.DeleteOneAsync(x => x.Key == key); + DeleteResult delete = await this._blacklist.DeleteOneAsync(x => x.Key == key); return delete.IsAcknowledged; } @@ -102,7 +108,7 @@ public async Task IsRevoked(string key) { try { - var item = await this._blacklist.Find(x => x.Key == key) + MongoBlackListItem item = await this._blacklist.Find(x => x.Key == key) .SingleAsync(); return item.ExpireOn > DateTime.Now; @@ -113,16 +119,20 @@ public async Task IsRevoked(string key) } } - public static async Task CreateStoreAsync(string dbName, MongoClientSettings clientSettings) + public static async Task CreateStoreAsync( + string dbName, + MongoClientSettings clientSettings) { - var client = new MongoClient(clientSettings); + MongoClient client = new(clientSettings); - var db = client.GetDatabase(dbName); + IMongoDatabase db = client.GetDatabase(dbName); - var keyIndex = Builders.IndexKeys.Ascending(x => x.Key); - var ttlIndex = Builders.IndexKeys.Ascending(x => x.ExpireOn); + IndexKeysDefinition keyIndex = Builders.IndexKeys.Ascending(x => x.Key); + IndexKeysDefinition ttlIndex = + Builders.IndexKeys.Ascending(x => x.ExpireOn); - var collection = db.GetCollection(nameof(MongoBlackListItem)); + IMongoCollection collection = + db.GetCollection(nameof(MongoBlackListItem)); await collection.Indexes.CreateOneAsync( new CreateIndexModel( diff --git a/Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj b/Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj index 59f9abf..afb08cd 100644 --- a/Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj +++ b/Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj @@ -1,5 +1,4 @@  - netstandard2.0 10.0 @@ -21,7 +20,6 @@ $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage True - diff --git a/Revoke.NET.MongoDB/RevokeService.cs b/Revoke.NET.MongoDB/RevokeService.cs index ad429c9..07464ff 100644 --- a/Revoke.NET.MongoDB/RevokeService.cs +++ b/Revoke.NET.MongoDB/RevokeService.cs @@ -8,12 +8,17 @@ public static class RevokeService public static IServiceCollection AddRevokeMongoStore(this IServiceCollection services) { return services.AddSingleton( - _ => MongoBlackList.CreateStoreAsync("RevokeStore", MongoClientSettings.FromConnectionString("mongodb://127.0.0.1:27017/RevokeStore")) + _ => MongoBlackList.CreateStoreAsync( + "RevokeStore", + MongoClientSettings.FromConnectionString("mongodb://127.0.0.1:27017/RevokeStore")) .GetAwaiter() .GetResult()); } - public static IServiceCollection AddRevokeMongoStore(this IServiceCollection services, string dbName, MongoClientSettings settings) + public static IServiceCollection AddRevokeMongoStore( + this IServiceCollection services, + string dbName, + MongoClientSettings settings) { return services.AddSingleton( _ => MongoBlackList.CreateStoreAsync(dbName, settings) diff --git a/Revoke.NET.Redis/RedisBlackList.cs b/Revoke.NET.Redis/RedisBlackList.cs index 1c9a6be..59db4b9 100644 --- a/Revoke.NET.Redis/RedisBlackList.cs +++ b/Revoke.NET.Redis/RedisBlackList.cs @@ -12,7 +12,9 @@ public class RedisBlackList : IBlackList private readonly IDatabase _blackList; private readonly IEnumerable _servers; - private RedisBlackList(IDatabase blackList, IEnumerable servers) + private RedisBlackList( + IDatabase blackList, + IEnumerable servers) { this._blackList = blackList; this._servers = servers; @@ -25,7 +27,7 @@ public async Task Delete(string key) public async Task DeleteAll() { - foreach (var key in this._servers.SelectMany(x => x.Keys())) + foreach (RedisKey key in this._servers.SelectMany(x => x.Keys())) { await this._blackList.KeyDeleteAsync(key); } @@ -33,40 +35,46 @@ public async Task DeleteAll() public async Task IsRevoked(string key) { - var value = await this._blackList.StringGetAsync(key); + RedisValue value = await this._blackList.StringGetAsync(key); return !value.HasValue; } public async Task Revoke(string key) { - var value = await this._blackList.StringSetAndGetAsync(key, key, _defaultTtl ?? TimeSpan.MaxValue); + RedisValue value = await this._blackList.StringSetAndGetAsync(key, key, _defaultTtl ?? TimeSpan.MaxValue); return value.HasValue; } - public async Task Revoke(string key, TimeSpan expireAfter) + public async Task Revoke( + string key, + TimeSpan expireAfter) { - var value = await this._blackList.StringSetAndGetAsync(key, key, expireAfter); + RedisValue value = await this._blackList.StringSetAndGetAsync(key, key, expireAfter); return value.HasValue; } - public async Task Revoke(string key, DateTime expireOn) + public async Task Revoke( + string key, + DateTime expireOn) { - var value = await this._blackList.StringSetAndGetAsync(key, key, expireOn - DateTimeOffset.Now); + RedisValue value = await this._blackList.StringSetAndGetAsync(key, key, expireOn - DateTimeOffset.Now); return value.HasValue; } - public static async Task CreateStoreAsync(string connectionString, TimeSpan? defaultTtl = null) + public static async Task CreateStoreAsync( + string connectionString, + TimeSpan? defaultTtl = null) { _defaultTtl = defaultTtl; - var options = ConfigurationOptions.Parse(connectionString); + ConfigurationOptions options = ConfigurationOptions.Parse(connectionString); options.AllowAdmin = true; - var redis = await ConnectionMultiplexer.ConnectAsync(options); - var blacklist = redis.GetDatabase(); - var servers = redis.GetEndPoints() + ConnectionMultiplexer redis = await ConnectionMultiplexer.ConnectAsync(options); + IDatabase blacklist = redis.GetDatabase(); + IEnumerable servers = redis.GetEndPoints() .Select(x => redis.GetServer(x)); return new RedisBlackList(blacklist, servers); diff --git a/Revoke.NET.Redis/Revoke.NET.Redis.csproj b/Revoke.NET.Redis/Revoke.NET.Redis.csproj index a8d5fa5..5b72eae 100644 --- a/Revoke.NET.Redis/Revoke.NET.Redis.csproj +++ b/Revoke.NET.Redis/Revoke.NET.Redis.csproj @@ -1,5 +1,4 @@ - netstandard2.0 10.0 @@ -21,12 +20,10 @@ $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage True - - diff --git a/Revoke.NET.Redis/RevokeService.cs b/Revoke.NET.Redis/RevokeService.cs index 1c981d4..43b7a03 100644 --- a/Revoke.NET.Redis/RevokeService.cs +++ b/Revoke.NET.Redis/RevokeService.cs @@ -12,7 +12,9 @@ public static IServiceCollection AddRevokeRedisStore(this IServiceCollection ser .GetResult()); } - public static IServiceCollection AddRevokeRedisStore(this IServiceCollection services, string connectionString) + public static IServiceCollection AddRevokeRedisStore( + this IServiceCollection services, + string connectionString) { return services.AddSingleton( _ => RedisBlackList.CreateStoreAsync(connectionString) diff --git a/Revoke.NET/IBlackList.cs b/Revoke.NET/IBlackList.cs index 00a5320..5ae2db4 100644 --- a/Revoke.NET/IBlackList.cs +++ b/Revoke.NET/IBlackList.cs @@ -1,19 +1,74 @@ namespace Revoke.NET; using System; +using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Primitives; public interface IBlackList { - Task Revoke(string key, TimeSpan expireAfter); + Task RevokeAsync(string key, TimeSpan expireAfter, CancellationToken cancellationToken = default); + + + + + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key, TimeSpan expireAfter, CancellationToken cancellationToken = default) instead.", + false)] + Task Revoke( + string key, + TimeSpan expireAfter); + - Task Revoke(string key, DateTime expireOn); + Task RevokeAsync( + string key, + DateTime expireOn, CancellationToken cancellationToken = default); + + + + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key, CancellationToken cancellationToken = default) instead.", + false)] + Task Revoke( + string key, + DateTime expireOn); + Task RevokeAsync(string key, CancellationToken cancellationToken = default); + + + + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key, CancellationToken cancellationToken = default) instead.", + false)] Task Revoke(string key); + + Task DeleteAsync(string key, CancellationToken cancellationToken = default); + + + + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAsync(string key, CancellationToken cancellationToken = default)instead.", + false)] Task Delete(string key); + + Task DeleteAllAsync(CancellationToken cancellationToken = default); + + + + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAllAsync(CancellationToken cancellationToken = default) instead.", + false)] Task DeleteAll(); + + Task IsRevokedAsync(string key, CancellationToken cancellationToken = default); + + + + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> IsRevokedAsync(string key, CancellationToken cancellationToken = default) instead.", + false)] Task IsRevoked(string key); } \ No newline at end of file diff --git a/Revoke.NET/Internals/RevokeGuardExtensions.cs b/Revoke.NET/Internals/RevokeGuardExtensions.cs new file mode 100644 index 0000000..c2df4a7 --- /dev/null +++ b/Revoke.NET/Internals/RevokeGuardExtensions.cs @@ -0,0 +1,27 @@ +namespace Revoke.NET.Internals; + +using System; + +internal static class Ensure +{ + public static class Is + { + public static void NotNullOrWhiteSpace( + string input, + string paramName = null) + { + string errorMessage = "Input parameter cannot be null or whitespace"; + if (!string.IsNullOrWhiteSpace(input)) + { + return; + } + + if (string.IsNullOrWhiteSpace(paramName)) + { + errorMessage = errorMessage.Replace("Input", paramName); + } + + throw new ArgumentException(errorMessage, paramName); + } + } +} \ No newline at end of file diff --git a/Revoke.NET/MemoryBlackList.cs b/Revoke.NET/MemoryBlackList.cs index 697268b..b89faa4 100644 --- a/Revoke.NET/MemoryBlackList.cs +++ b/Revoke.NET/MemoryBlackList.cs @@ -2,7 +2,9 @@ using System; using System.Collections.Concurrent; +using System.Threading; using System.Threading.Tasks; +using Internals; public class MemoryBlackList : IBlackList { @@ -15,18 +17,37 @@ private MemoryBlackList(TimeSpan? defaultTtl) this._blackList = new ConcurrentDictionary(); } + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAsync(string string, CancellationToken cancellationToken = default) instead.", + false)] public Task Delete(string key) { + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + return Task.FromResult(this._blackList.TryRemove(key, out _)); } - public Task Revoke(string key, TimeSpan expireAfter) + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key, TimeSpan expireAfter, CancellationToken cancellationToken = default) instead.", + false)] + public Task Revoke( + string key, + TimeSpan expireAfter) { + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + return Task.FromResult(this._blackList.TryAdd(key, DateTime.Now.Add(expireAfter))); } - public Task Revoke(string key, DateTime expireOn) + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key, DateTime expireOn, CancellationToken cancellationToken = default) instead.", + false)] + public Task Revoke( + string key, + DateTime expireOn) { + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + if (expireOn < DateTimeOffset.Now) { return Task.FromResult(false); @@ -35,6 +56,9 @@ public Task Revoke(string key, DateTime expireOn) return Task.FromResult(this._blackList.TryAdd(key, expireOn)); } + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAllAsync(CancellationToken cancellationToken = default) instead.", + false)] public Task DeleteAll() { this._blackList.Clear(); @@ -42,9 +66,13 @@ public Task DeleteAll() return Task.CompletedTask; } + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> IsRevokedAsync(string key, CancellationToken cancellationToken = default) instead.", + false)] public Task IsRevoked(string key) { - if (this._blackList.TryGetValue(key, out var item)) + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + if (this._blackList.TryGetValue(key, out DateTime item)) { return Task.FromResult(item >= DateTime.Now); } @@ -52,8 +80,95 @@ public Task IsRevoked(string key) return Task.FromResult(false); } + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key, CancellationToken cancellationToken = default) instead.", + false)] public Task Revoke(string key) { + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + + if (DateTime.Now.Add(this._defaultTtl ?? TimeSpan.MaxValue) < DateTime.Now) + { + return Task.FromResult(false); + } + + return Task.FromResult(this._blackList.TryAdd(key, DateTime.Now.Add(this._defaultTtl ?? TimeSpan.MaxValue))); + } + + public Task DeleteAsync( + string key, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + + return Task.FromResult(this._blackList.TryRemove(key, out _)); + } + + public Task RevokeAsync( + string key, + TimeSpan expireAfter, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + + return Task.FromResult(this._blackList.TryAdd(key, DateTime.Now.Add(expireAfter))); + } + + public Task RevokeAsync( + string key, + DateTime expireOn, + CancellationToken cancellationToken = default) + + { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + + if (expireOn < DateTimeOffset.Now) + { + return Task.FromResult(false); + } + + return Task.FromResult(this._blackList.TryAdd(key, expireOn)); + } + + public Task DeleteAllAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + this._blackList.Clear(); + + return Task.CompletedTask; + } + + public Task IsRevokedAsync( + string key, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + + if (this._blackList.TryGetValue(key, out DateTime item)) + { + return Task.FromResult(item >= DateTime.Now); + } + + return Task.FromResult(false); + } + + public Task RevokeAsync( + string key, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + if (DateTime.Now.Add(this._defaultTtl ?? TimeSpan.MaxValue) < DateTime.Now) { return Task.FromResult(false); diff --git a/Revoke.NET/MemoryCacheBlackList.cs b/Revoke.NET/MemoryCacheBlackList.cs index 17142cf..795fe11 100644 --- a/Revoke.NET/MemoryCacheBlackList.cs +++ b/Revoke.NET/MemoryCacheBlackList.cs @@ -12,15 +12,18 @@ public class MemoryCacheBlackList : IBlackList private readonly TimeSpan? _defaultTtl; private readonly IMemoryCache _memoryCache; - public MemoryCacheBlackList(IMemoryCache memoryCache, TimeSpan? defaultTtl = null) + public MemoryCacheBlackList( + IMemoryCache memoryCache, + TimeSpan? defaultTtl = null) { this._defaultTtl = defaultTtl; this._memoryCache = memoryCache; } - + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,CancellationToken cancellationToken = default) instead.", false)] public Task Revoke(string key) { - var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(this._defaultTtl ?? TimeSpan.MaxValue); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); try @@ -34,8 +37,41 @@ public Task Revoke(string key) return Task.FromResult(false); } } + + public Task RevokeAsync(string key, CancellationToken cancellationToken = default) + { + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + .SetAbsoluteExpiration(this._defaultTtl ?? TimeSpan.MaxValue); + options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); + try + { + this._memoryCache.Set(key, key, options); + return Task.FromResult(true); + } + catch + { + return Task.FromResult(false); + } + } + + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAsync(string key,CancellationToken cancellationToken = default) instead.", false)] public Task Delete(string key) + { + try + { + this._memoryCache.Remove(key); + + return Task.FromResult(true); + } + catch + { + return Task.FromResult(false); + } + } + + public Task DeleteAsync(string key,CancellationToken cancellationToken = default) { try { @@ -48,10 +84,27 @@ public Task Delete(string key) return Task.FromResult(false); } } + + + public Task DeleteAllAsync(CancellationToken cancellationToken = default) + { + if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && + _resetCacheToken.Token.CanBeCanceled) + { + _resetCacheToken.Cancel(); + _resetCacheToken.Dispose(); + } + _resetCacheToken = new CancellationTokenSource(); + + return Task.CompletedTask; + } + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAllAsync(CancellationToken cancellationToken = default) instead.", false)] public Task DeleteAll() { - if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && _resetCacheToken.Token.CanBeCanceled) + if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && + _resetCacheToken.Token.CanBeCanceled) { _resetCacheToken.Cancel(); _resetCacheToken.Dispose(); @@ -62,14 +115,44 @@ public Task DeleteAll() return Task.CompletedTask; } + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> IsRevokedAsync(string key, CancellationToken cancellationToken = default) instead.", false)] public Task IsRevoked(string key) { return Task.FromResult(this._memoryCache.TryGetValue(key, out _)); } + public Task IsRevokedAsync(string key, CancellationToken cancellationToken = default) + { + return Task.FromResult(this._memoryCache.TryGetValue(key, out _)); + } + + public Task RevokeAsync( + string key, + TimeSpan expireAfter, CancellationToken cancellationToken = default) + { + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + .SetAbsoluteExpiration(expireAfter); + options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); + try + { + this._memoryCache.Set(key, key, options); + + return Task.FromResult(true); + } + catch + { + return Task.FromResult(false); + } + } + - public Task Revoke(string key, TimeSpan expireAfter) + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,TimeSpan expireOn, CancellationToken cancellationToken = default) instead.", false)] + public Task Revoke( + string key, + TimeSpan expireAfter) { - var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(expireAfter); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); try @@ -83,10 +166,34 @@ public Task Revoke(string key, TimeSpan expireAfter) return Task.FromResult(false); } } + + public Task RevokeAsync( + string key, + DateTime expireOn, CancellationToken cancellationToken = default) + { + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + .SetAbsoluteExpiration(expireOn); + options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); + + try + { + this._memoryCache.Set(key, key, options); + + return Task.FromResult(true); + } + catch + { + return Task.FromResult(false); + } + } - public Task Revoke(string key, DateTime expireOn) + [Obsolete( + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,DateTime expireOn, CancellationToken cancellationToken = default) instead.", false)] + public Task Revoke( + string key, + DateTime expireOn) { - var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(expireOn); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); diff --git a/Revoke.NET/Revoke.NET.csproj b/Revoke.NET/Revoke.NET.csproj index 4ce8967..771e734 100644 --- a/Revoke.NET/Revoke.NET.csproj +++ b/Revoke.NET/Revoke.NET.csproj @@ -1,5 +1,4 @@  - netstandard2.0;netstandard2.1;net6.0 10.0 diff --git a/Revoke.NET/RevokeService.cs b/Revoke.NET/RevokeService.cs index 8462f35..0c89e7e 100644 --- a/Revoke.NET/RevokeService.cs +++ b/Revoke.NET/RevokeService.cs @@ -16,9 +16,12 @@ public static class RevokeService /// The services /// The default ttl /// The services - public static IServiceCollection AddRevokeMemoryCacheStore(this IServiceCollection services, TimeSpan? defaultTtl = null) + public static IServiceCollection AddRevokeMemoryCacheStore( + this IServiceCollection services, + TimeSpan? defaultTtl = null) { - services.TryAddSingleton(provider => new MemoryCacheBlackList(provider.GetService(), defaultTtl)); + services.TryAddSingleton( + provider => new MemoryCacheBlackList(provider.GetService(), defaultTtl)); return services; } @@ -29,7 +32,9 @@ public static IServiceCollection AddRevokeMemoryCacheStore(this IServiceCollecti /// /// Default Blacklist Item Expiration Duration, null mean no expiration /// - public static IServiceCollection AddRevokeInMemoryStore(this IServiceCollection services, TimeSpan? defaultTtl = null) + public static IServiceCollection AddRevokeInMemoryStore( + this IServiceCollection services, + TimeSpan? defaultTtl = null) { services.TryAddSingleton(MemoryBlackList.CreateStore(defaultTtl)); @@ -42,7 +47,9 @@ public static IServiceCollection AddRevokeInMemoryStore(this IServiceCollection /// /// /// - public static IServiceCollection AddRevokeStore(this IServiceCollection services, Func configure) + public static IServiceCollection AddRevokeStore( + this IServiceCollection services, + Func configure) { services.TryAddSingleton(configure()); @@ -55,7 +62,9 @@ public static IServiceCollection AddRevokeStore(this IServiceCollection services /// /// /// - public static IServiceCollection AddRevokeStore(this IServiceCollection services, Func configure) + public static IServiceCollection AddRevokeStore( + this IServiceCollection services, + Func configure) { services.TryAddSingleton(configure); diff --git a/Test/Program.cs b/Test/Program.cs index 5de0e00..980239b 100644 --- a/Test/Program.cs +++ b/Test/Program.cs @@ -1,10 +1,11 @@ -using Revoke.NET.Redis; +using Revoke.NET; +using Revoke.NET.Redis; -var store = await RedisBlackList.CreateStoreAsync("localhost"); +IBlackList? store = await RedisBlackList.CreateStoreAsync("localhost"); await store.Revoke("Ahmed", DateTime.MaxValue); -var revoked = await store.IsRevoked("Ahmed"); +bool revoked = await store.IsRevoked("Ahmed"); Console.WriteLine(revoked); diff --git a/Test/Test.csproj b/Test/Test.csproj index 76df675..d2ea8ad 100644 --- a/Test/Test.csproj +++ b/Test/Test.csproj @@ -1,16 +1,13 @@  - Exe net6.0 enable enable - - From 122493c67b00d680ed2157e1e3f4a7fa562dcb2e Mon Sep 17 00:00:00 2001 From: Jeff Ward Date: Wed, 11 Jan 2023 11:04:10 -0500 Subject: [PATCH 2/2] added missing guard clauses --- Revoke.NET/MemoryCacheBlackList.cs | 86 +++++++++++++++++++++++------- 1 file changed, 67 insertions(+), 19 deletions(-) diff --git a/Revoke.NET/MemoryCacheBlackList.cs b/Revoke.NET/MemoryCacheBlackList.cs index 795fe11..4e828b9 100644 --- a/Revoke.NET/MemoryCacheBlackList.cs +++ b/Revoke.NET/MemoryCacheBlackList.cs @@ -3,6 +3,7 @@ using System; using System.Threading; using System.Threading.Tasks; +using Internals; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Primitives; @@ -19,10 +20,14 @@ public MemoryCacheBlackList( this._defaultTtl = defaultTtl; this._memoryCache = memoryCache; } + [Obsolete( - "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,CancellationToken cancellationToken = default) instead.", false)] + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,CancellationToken cancellationToken = default) instead.", + false)] public Task Revoke(string key) { + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(this._defaultTtl ?? TimeSpan.MaxValue); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); @@ -37,9 +42,15 @@ public Task Revoke(string key) return Task.FromResult(false); } } - - public Task RevokeAsync(string key, CancellationToken cancellationToken = default) + + public Task RevokeAsync( + string key, + CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(this._defaultTtl ?? TimeSpan.MaxValue); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); @@ -54,15 +65,18 @@ public Task RevokeAsync(string key, CancellationToken cancellationToken = return Task.FromResult(false); } } - + [Obsolete( - "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAsync(string key,CancellationToken cancellationToken = default) instead.", false)] + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAsync(string key,CancellationToken cancellationToken = default) instead.", + false)] public Task Delete(string key) { + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + try { this._memoryCache.Remove(key); - + return Task.FromResult(true); } catch @@ -70,9 +84,15 @@ public Task Delete(string key) return Task.FromResult(false); } } - - public Task DeleteAsync(string key,CancellationToken cancellationToken = default) + + public Task DeleteAsync( + string key, + CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + try { this._memoryCache.Remove(key); @@ -84,10 +104,11 @@ public Task DeleteAsync(string key,CancellationToken cancellationToken = d return Task.FromResult(false); } } - - + public Task DeleteAllAsync(CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && _resetCacheToken.Token.CanBeCanceled) { @@ -99,8 +120,10 @@ public Task DeleteAllAsync(CancellationToken cancellationToken = default) return Task.CompletedTask; } + [Obsolete( - "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAllAsync(CancellationToken cancellationToken = default) instead.", false)] + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> DeleteAllAsync(CancellationToken cancellationToken = default) instead.", + false)] public Task DeleteAll() { if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && @@ -116,20 +139,33 @@ public Task DeleteAll() } [Obsolete( - "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> IsRevokedAsync(string key, CancellationToken cancellationToken = default) instead.", false)] + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> IsRevokedAsync(string key, CancellationToken cancellationToken = default) instead.", + false)] public Task IsRevoked(string key) { return Task.FromResult(this._memoryCache.TryGetValue(key, out _)); } - public Task IsRevokedAsync(string key, CancellationToken cancellationToken = default) + + public Task IsRevokedAsync( + string key, + CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + return Task.FromResult(this._memoryCache.TryGetValue(key, out _)); } public Task RevokeAsync( string key, - TimeSpan expireAfter, CancellationToken cancellationToken = default) + TimeSpan expireAfter, + CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(expireAfter); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); @@ -145,13 +181,16 @@ public Task RevokeAsync( } } - [Obsolete( - "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,TimeSpan expireOn, CancellationToken cancellationToken = default) instead.", false)] + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,TimeSpan expireOn, CancellationToken cancellationToken = default) instead.", + false)] public Task Revoke( string key, TimeSpan expireAfter) { + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(expireAfter); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); @@ -166,11 +205,16 @@ public Task Revoke( return Task.FromResult(false); } } - + public Task RevokeAsync( string key, - DateTime expireOn, CancellationToken cancellationToken = default) + DateTime expireOn, + CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(expireOn); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); @@ -188,11 +232,15 @@ public Task RevokeAsync( } [Obsolete( - "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,DateTime expireOn, CancellationToken cancellationToken = default) instead.", false)] + "This method is obsolete. Later versions of Revoke.NET will utilize the `Async` suffix on async methods with the addition of cancellation token parameters. Please use >> RevokeAsync(string key,DateTime expireOn, CancellationToken cancellationToken = default) instead.", + false)] public Task Revoke( string key, DateTime expireOn) { + + Ensure.Is.NotNullOrWhiteSpace(key, nameof(key)); + MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) .SetAbsoluteExpiration(expireOn); options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));