aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLibravatar vnugent <public@vaughnnugent.com>2023-03-09 01:48:40 -0500
committerLibravatar vnugent <public@vaughnnugent.com>2023-03-09 01:48:40 -0500
commitd673bd34945699df96e38c54f70352608430fbc4 (patch)
treedd5e17d02f3fe73e4d1a54689bd9c7d41f1a5a71
parent11a8cea8a6445bd5127eb4c97fc582cd944f72ea (diff)
Omega cache, session, and account provider complete overhaul
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/GlobalCacheStore.cs18
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteCacheStore.cs4
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteSession.cs73
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionFactory.cs47
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionIdFactory.cs74
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionSerialzer.cs46
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionStore.cs60
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/RemoteSession.cs170
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionCacheClient.cs251
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionDataSerialzer.cs150
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionSerializer.cs352
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionStatus.cs53
-rw-r--r--libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionStore.cs312
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/LICENSE.txt195
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/README.md11
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/build.readme.md0
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/src/MemSessionPluginEntry.cs71
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/src/MemorySession.cs129
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionConfig.cs58
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionEntrypoint.cs95
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionStore.cs168
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/src/SessionIdFactory.cs81
-rw-r--r--libs/VNLib.Plugins.Sessions.Memory/src/VNLib.Plugins.Sessions.Memory.csproj49
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/AccessTokenEndpoint.cs20
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/RevocationEndpoint.cs8
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/GetTokenResult.cs36
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/IApplicationTokenFactory.cs (renamed from libs/VNLib.Plugins.Sessions.OAuth/src/TokenAndSessionIdResult.cs)27
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/IOauthSessionIdFactory.cs27
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/O2SessionProviderEntry.cs65
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2Session.cs83
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionConfig.cs70
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionFactory.cs41
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionIdProvider.cs131
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionProvider.cs212
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionStore.cs101
-rw-r--r--libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2TokenFactory.cs99
-rw-r--r--libs/VNLib.Plugins.Sessions.VNCache/src/WebSession.cs81
-rw-r--r--libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionFactory.cs56
-rw-r--r--libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionIdFactory.cs100
-rw-r--r--libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionIdFactoryImpl.cs120
-rw-r--r--libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProvider.cs158
-rw-r--r--libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProviderEntry.cs39
-rw-r--r--libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionStore.cs150
-rw-r--r--plugins/SessionProvider/src/RuntimeSessionProvider.cs4
-rw-r--r--plugins/SessionProvider/src/SessionProviderEntry.cs (renamed from plugins/SessionProvider/src/SessionClientEntryPoint.cs)98
45 files changed, 2229 insertions, 1964 deletions
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/GlobalCacheStore.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/GlobalCacheStore.cs
index 55f5016..bb7acd6 100644
--- a/libs/VNLib.Plugins.Sessions.Cache.Client/src/GlobalCacheStore.cs
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/GlobalCacheStore.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Sessions.Cache.Client
@@ -30,6 +30,7 @@ using VNLib.Data.Caching;
namespace VNLib.Plugins.Sessions.Cache.Client
{
+
/// <summary>
/// A wrapper class to provide a <see cref="IRemoteCacheStore"/> from
/// a <see cref="IGlobalCacheProvider"/> client instance
@@ -37,10 +38,19 @@ namespace VNLib.Plugins.Sessions.Cache.Client
public sealed class GlobalCacheStore : IRemoteCacheStore
{
private readonly IGlobalCacheProvider _cache;
+
+ private readonly SessionDataSerialzer _serialzer;
+ /// <summary>
+ /// Initiailzes a new <see cref="GlobalCacheStore"/> with the backing <see cref="IGlobalCacheProvider"/>
+ /// global cache
+ /// </summary>
+ /// <param name="globalCache"></param>
+ /// <exception cref="ArgumentNullException"></exception>
public GlobalCacheStore(IGlobalCacheProvider globalCache)
{
_cache = globalCache ?? throw new ArgumentNullException(nameof(globalCache));
+ _serialzer = new();
}
///<inheritdoc/>
@@ -49,9 +59,9 @@ namespace VNLib.Plugins.Sessions.Cache.Client
///<inheritdoc/>
public Task AddOrUpdateObjectAsync<T>(string objectId, string? newId, T obj, CancellationToken cancellationToken = default)
{
- return _cache.AddOrUpdateAsync(objectId, newId, obj, cancellationToken);
+ return _cache.AddOrUpdateAsync(objectId, newId, obj, _serialzer, cancellationToken);
}
-
+
///<inheritdoc/>
public Task DeleteObjectAsync(string objectId, CancellationToken cancellationToken = default)
{
@@ -61,7 +71,7 @@ namespace VNLib.Plugins.Sessions.Cache.Client
///<inheritdoc/>
public Task<T?> GetObjectAsync<T>(string objectId, CancellationToken cancellationToken = default)
{
- return _cache.GetAsync<T>(objectId, cancellationToken);
+ return _cache.GetAsync<T>(objectId, _serialzer, cancellationToken);
}
}
}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteCacheStore.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteCacheStore.cs
index ce95a6b..aa2e3a7 100644
--- a/libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteCacheStore.cs
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteCacheStore.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Sessions.Cache.Client
@@ -37,7 +37,7 @@ namespace VNLib.Plugins.Sessions.Cache.Client
/// </summary>
/// <typeparam name="T">The data type</typeparam>
/// <param name="objectId">The key/id of the object to recover</param>
- /// <param name="cancellationToken">A token to cancel the operation</param>
+ /// <param name="cancellationToken">An optional token to cancel the operation</param>
/// <returns>A task that resolves the found object or null otherwise</returns>
Task<T?> GetObjectAsync<T>(string objectId, CancellationToken cancellationToken = default);
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteSession.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteSession.cs
new file mode 100644
index 0000000..d88fee2
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/IRemoteSession.cs
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: IRemoteSession.cs
+*
+* IRemoteSession.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+using System.Collections.Generic;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+ /// <summary>
+ /// A session that is expected to be stored in a remote caching storage system
+ /// </summary>
+ public interface IRemoteSession
+ {
+ /// <summary>
+ /// Gets the ID of the session
+ /// </summary>
+ string SessionID { get; }
+
+ /// <summary>
+ /// Gets the status of the session during a release operation
+ /// </summary>
+ /// <returns>The <see cref="SessionStatus"/> flags that represent the status of the session</returns>
+ SessionStatus GetStatus();
+
+ /// <summary>
+ /// Gets the internal session data to update when requested
+ /// </summary>
+ /// <returns>The internal session data</returns>
+ IDictionary<string, string> GetSessionData();
+
+ /// <summary>
+ /// Destroys the internal state of the session so it cannot be
+ /// reused
+ /// </summary>
+ /// <param name="cause">A optional exception that caused the error condition</param>
+ void Destroy(Exception? cause);
+
+ /// <summary>
+ /// Determines if the state of the session is valid for reuse by a waiting
+ /// connection. Optionally returns an exception that caused
+ /// </summary>
+ /// <param name="cause">The exception that caused the session state to transition to invalid</param>
+ /// <returns>True of the session is valid, false if it cannot be reused</returns>
+ bool IsValid(out Exception? cause);
+
+ /// <summary>
+ /// Called by the store to notify the session that a pending update has completed
+ /// successfully.
+ /// </summary>
+ void SessionUpdateComplete();
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionFactory.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionFactory.cs
new file mode 100644
index 0000000..ea1646e
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionFactory.cs
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: ISessionFactory.cs
+*
+* ISessionFactory.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System.Collections.Generic;
+
+using VNLib.Net.Http;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+ /// <summary>
+ /// A session factory that generates new sessions on demand by a <see cref="ISessionStore{TSession}"/>
+ /// </summary>
+ /// <typeparam name="TSession">The session type to generate</typeparam>
+ public interface ISessionFactory<TSession>
+ {
+ /// <summary>
+ /// Constructs a new session of the given type from the session Id
+ /// and its initial object data
+ /// </summary>
+ /// <param name="sessionId">The is of the session to create</param>
+ /// <param name="sessionData">The initial session data to create the session from</param>
+ /// <param name="entity">The connection to get the session for</param>
+ /// <returns>The new session</returns>
+ TSession? GetNewSession(IHttpEvent entity, string sessionId, IDictionary<string, string>? sessionData);
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionIdFactory.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionIdFactory.cs
new file mode 100644
index 0000000..d423ae2
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionIdFactory.cs
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: ISessionIdFactory.cs
+*
+* ISessionIdFactory.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using VNLib.Net.Http;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+ /// <summary>
+ /// A factory that gets sessionIds from connections and regenerates
+ /// session ids on connections if supported
+ /// </summary>
+ public interface ISessionIdFactory
+ {
+ /// <summary>
+ /// A value that indicates if session id regeneration
+ /// will be supported by this provider
+ /// </summary>
+ bool RegenerationSupported { get; }
+
+ /// <summary>
+ /// A value that indicates if a session id should be
+ /// regenerated when the remote cache does not have a
+ /// result for the recovered id
+ /// </summary>
+ /// <remarks>
+ /// This is considered a security feature to dissalow clients
+ /// from injecting thier own sessions
+ /// </remarks>
+ bool RegenIdOnEmptyEntry { get; }
+
+ /// <summary>
+ /// Indicates if the request can be serviced
+ /// </summary>
+ /// <param name="entity">The entity to service</param>
+ /// <returns>True if a session id can be provided for this connection</returns>
+ bool CanService(IHttpEvent entity);
+
+ /// <summary>
+ /// Regenerates the session id for the given connection
+ /// </summary>
+ /// <param name="entity">The connection to regenreate the id for</param>
+ /// <returns>The new session id for the connection, or null if regeneration fails</returns>
+ string RegenerateId(IHttpEvent entity);
+
+ /// <summary>
+ /// Attempts to recover a session id from the connection. If null is
+ /// returned it is consisdered a failure.
+ /// </summary>
+ /// <param name="entity">The connection to retrieve the sessionId for</param>
+ /// <returns>The session id if successfull, null otherwise</returns>
+ string? TryGetSessionId(IHttpEvent entity);
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionSerialzer.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionSerialzer.cs
new file mode 100644
index 0000000..40bfa7b
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionSerialzer.cs
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: ISessionSerialzer.cs
+*
+* ISessionSerialzer.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System.Diagnostics.CodeAnalysis;
+
+using VNLib.Utils.Async;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+ /// <summary>
+ /// A specialized <see cref="IAsyncAccessSerializer{TMoniker}"/>
+ /// that allows for re-using an instance that may be awaited
+ /// </summary>
+ /// <typeparam name="TSession">The session type</typeparam>
+ public interface ISessionSerialzer<TSession> : IAsyncAccessSerializer<TSession>
+ {
+ /// <summary>
+ /// Attempts to get an active session in the wait table as an atomic operation
+ /// </summary>
+ /// <param name="sessionId">The id of the session to retreive from the store</param>
+ /// <param name="session">The stored session</param>
+ /// <returns>A value that inidcates if the session was found</returns>
+ bool TryGetSession(string sessionId, [NotNullWhen(true)] out TSession? session);
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionStore.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionStore.cs
new file mode 100644
index 0000000..8e595dc
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/ISessionStore.cs
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: ISessionStore.cs
+*
+* ISessionStore.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System.Threading;
+using System.Threading.Tasks;
+
+using VNLib.Net.Http;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+ /// <summary>
+ /// A store for session types that attaches sessions to incomming http connections
+ /// </summary>
+ /// <typeparam name="TSession">The session type</typeparam>
+ public interface ISessionStore<TSession>
+ {
+ /// <summary>
+ /// Gets a session for the given connection or returns null if no
+ /// session could be attached to the connection
+ /// </summary>
+ /// <param name="entity">The connection to attach a session to</param>
+ /// <param name="cancellationToken">A token to cancel that async operation</param>
+ /// <returns>The session for the incomming connection, or null if no session was found</returns>
+ ValueTask<TSession?> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Releases the session from the connection, as its no longer required. Cleanup tasks
+ /// should be performed while the connection is still alive
+ /// </summary>
+ /// <param name="session">The session to detach</param>
+ /// <param name="entity">The connection the session is attached to</param>
+ /// <returns>A task that completes when the session has been detached</returns>
+ /// <remarks>
+ /// The connection results/request should not be modified. Cookies/headers
+ /// may still be valid
+ /// </remarks>
+ ValueTask ReleaseSessionAsync(TSession session, IHttpEvent entity);
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/RemoteSession.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/RemoteSession.cs
index af2c969..421d07d 100644
--- a/libs/VNLib.Plugins.Sessions.Cache.Client/src/RemoteSession.cs
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/RemoteSession.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Sessions.Cache.Client
@@ -23,85 +23,49 @@
*/
using System;
-using System.Threading;
-using System.Threading.Tasks;
using System.Collections.Generic;
-using Microsoft.VisualStudio.Threading;
-
-using VNLib.Net.Http;
-using VNLib.Data.Caching.Exceptions;
using VNLib.Utils.Extensions;
using VNLib.Plugins.Essentials.Sessions;
using VNLib.Plugins.Essentials.Extensions;
+
namespace VNLib.Plugins.Sessions.Cache.Client
{
/// <summary>
/// Base class for cacheable lazy initialized session entires
/// that exist in a remote caching server
/// </summary>
- public abstract class RemoteSession : SessionBase
+ public abstract class RemoteSession : SessionBase, IRemoteSession
{
protected const string CREATED_TIME_ENTRY = "__.i.ctime";
-
- protected IRemoteCacheStore Client { get; }
- protected TimeSpan UpdateTimeout { get; }
- private readonly AsyncLazyInitializer Initializer;
-
/// <summary>
- /// The lazy loaded data-store
+ /// The session data store
/// </summary>
- protected Dictionary<string, string>? DataStore;
-
- protected RemoteSession(string sessionId, IRemoteCacheStore client, TimeSpan backgroundTimeOut)
- {
- SessionID = sessionId;
- UpdateTimeout = backgroundTimeOut;
- Client = client;
- Initializer = new(InitializeAsync, null);
- }
+ protected readonly IDictionary<string, string> DataStore;
/// <summary>
- /// The data initializer, loads the data store from the connected cache server
+ /// The reason that the session was destroyed if an error occured
/// </summary>
- /// <returns>A task that completes when the get operation completes</returns>
- protected virtual async Task InitializeAsync()
- {
- //Setup timeout cancellation for the get, to cancel it
- using CancellationTokenSource cts = new(UpdateTimeout);
- //get or create a new session
- DataStore = await Client.GetObjectAsync<Dictionary<string, string>>(SessionID, cancellationToken: cts.Token);
- }
- /// <summary>
- /// Updates the current sessin agaisnt the cache store
- /// </summary>
- /// <returns>A task that complets when the update has completed</returns>
- protected virtual async Task ProcessUpdateAsync()
- {
- //Setup timeout cancellation for the update, to cancel it
- using CancellationTokenSource cts = new(UpdateTimeout);
- await Client.AddOrUpdateObjectAsync(SessionID, null, DataStore, cts.Token);
- }
+ protected Exception? ErrorCause { get; set; }
+
/// <summary>
- /// Delets the current session in the remote store
+ /// Initialzies a new session
/// </summary>
- /// <returns>A task that completes when instance has been deleted</returns>
- protected virtual async Task ProcessDeleteAsync()
+ /// <param name="sessionId">The id of the current session</param>
+ /// <param name="initialData">The initial data</param>
+ /// <param name="isNew">A flag that determines if the session is considered new</param>
+ protected RemoteSession(string sessionId, IDictionary<string, string> initialData, bool isNew)
{
- //Setup timeout cancellation for the update, to cancel it
- using CancellationTokenSource cts = new(UpdateTimeout);
- try
- {
- await Client.DeleteObjectAsync(SessionID, cts.Token);
- }
- catch (ObjectNotFoundException)
- {
- //This is fine, if the object does not exist, nothing to invalidate
- }
+ SessionID = sessionId;
+ DataStore = initialData;
+ IsNew = isNew;
}
-
+
+ ///<inheritdoc/>
+ public override string SessionID { get; }
+
///<inheritdoc/>
public override DateTimeOffset Created
{
@@ -113,15 +77,14 @@ namespace VNLib.Plugins.Sessions.Cache.Client
return DateTimeOffset.FromUnixTimeMilliseconds(unixMs);
}
- protected set => this.SetValueType(CREATED_TIME_ENTRY, value.ToUnixTimeMilliseconds());
- }
-
+ set => this.SetValueType(CREATED_TIME_ENTRY, value.ToUnixTimeMilliseconds());
+ }
///<inheritdoc/>
protected override string IndexerGet(string key)
{
//Get the value at the key or an empty string as a default
- return DataStore!.GetValueOrDefault(key, string.Empty);
+ return DataStore.GetValueOrDefault(key) ?? string.Empty;
}
///<inheritdoc/>
protected override void IndexerSet(string key, string value)
@@ -130,59 +93,60 @@ namespace VNLib.Plugins.Sessions.Cache.Client
if (value == null)
{
//Set modified flag
- IsModified |= DataStore!.Remove(key);
+ IsModified |= DataStore.Remove(key);
}
else
{
//Store the value at the specified key
- DataStore![key] = value;
+ DataStore[key] = value;
IsModified = true;
}
}
+
-
- /*
- * If the data-store is not found it means the session does not
- * exist in cache, so its technically not dangerous to reuse,
- * so the new mask needs to be set, but the old ID is going
- * to be reused
- */
+ ///<inheritdoc/>
+ public virtual SessionStatus GetStatus()
+ {
+ SessionStatus status = SessionStatus.None;
- /// <summary>
- /// Waits for exclusive access to the session, and initializes
- /// session data (loads it from the remote store)
- /// </summary>
- /// <param name="entity">The event to attach a session to</param>
- /// <param name="cancellationToken">A token to cancel the operaion</param>
- /// <returns></returns>
- public virtual async Task WaitAndLoadAsync(IHttpEvent entity, CancellationToken cancellationToken)
+ status |= Flags.IsSet(INVALID_MSK) ? SessionStatus.Delete : SessionStatus.None;
+ status |= Flags.IsSet(REGEN_ID_MSK) ? SessionStatus.RegenId : SessionStatus.None;
+ status |= Flags.IsSet(MODIFIED_MSK) ? SessionStatus.UpdateOnly: SessionStatus.None;
+
+ return status;
+ }
+
+ ///<inheritdoc/>
+ public virtual IDictionary<string, string> GetSessionData() => DataStore;
+
+ ///<inheritdoc/>
+ public virtual void Destroy(Exception? cause)
{
- //Wait for exclusive access
- await base.WaitOneAsync(cancellationToken);
- try
- {
- //Lazily initalize the current instance
- await Initializer.InitializeAsync(cancellationToken);
- //See if data-store is null (new session was created
- if (DataStore == null)
- {
- //New session was created
- DataStore = new(10);
- //Set is-new flag
- Flags.Set(IS_NEW_MSK);
- //Set created time
- Created = DateTimeOffset.UtcNow;
- //Init ipaddress
- UserIP = entity.Server.GetTrustedIp();
- //Set modified flag so session will be updated
- IsModified = true;
- }
- }
- catch
- {
- MainLock.Release();
- throw;
- }
+ //Set invalid status
+ ErrorCause = cause;
+ Flags.Set(INVALID_MSK);
+
+ //Clear all session data
+ DataStore.Clear();
+ }
+
+ ///<inheritdoc/>
+ public virtual bool IsValid(out Exception? cause)
+ {
+ /*
+ * Were reusing the invalid mask assuming that when a session is invalidated
+ * it will be deleted and destroyed
+ */
+
+ cause = ErrorCause;
+ return !Flags.IsSet(INVALID_MSK);
+ }
+
+ ///<inheritdoc/>
+ public virtual void SessionUpdateComplete()
+ {
+ //Reset flags
+ Flags.ClearAll();
}
}
}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionCacheClient.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionCacheClient.cs
deleted file mode 100644
index 20ea947..0000000
--- a/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionCacheClient.cs
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Sessions.Cache.Client
-* File: SessionCacheClient.cs
-*
-* SessionCacheClient.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-
-using VNLib.Net.Http;
-using VNLib.Utils.Async;
-using VNLib.Utils.Logging;
-using VNLib.Utils.Memory.Caching;
-using VNLib.Plugins.Essentials.Sessions;
-
-namespace VNLib.Plugins.Sessions.Cache.Client
-{
-
- /// <summary>
- /// A client that allows access to sessions located on external servers
- /// </summary>
- public abstract class SessionCacheClient : ICacheHolder
- {
- public class LRUSessionStore<T> : LRUCache<string, T>, ICacheHolder where T : ISession
- {
- internal AsyncQueue<T> ExpiredSessions { get; }
-
- ///<inheritdoc/>
- public override bool IsReadOnly => false;
- ///<inheritdoc/>
- protected override int MaxCapacity { get; }
-
-
- public LRUSessionStore(int maxCapacity) : base(StringComparer.Ordinal)
- {
- MaxCapacity = maxCapacity;
- ExpiredSessions = new (true, true);
- }
-
- ///<inheritdoc/>
- protected override bool CacheMiss(string key, [NotNullWhen(true)] out T? value)
- {
- value = default;
- return false;
- }
-
- ///<inheritdoc/>
- protected override void Evicted(ref KeyValuePair<string, T> evicted)
- {
- //add to queue, the list lock should be held during this operatio
- _ = ExpiredSessions.TryEnque(evicted.Value);
- }
-
- ///<inheritdoc/>
- public void CacheClear()
- {
- foreach (KeyValuePair<string, T> value in List)
- {
- KeyValuePair<string, T> onStack = value;
-
- Evicted(ref onStack);
- }
-
- Clear();
- }
-
- ///<inheritdoc/>
- public void CacheHardClear()
- {
- CacheClear();
- }
- }
-
- protected readonly LRUSessionStore<RemoteSession> CacheTable;
- protected readonly object CacheLock;
- protected readonly int MaxLoadedEntires;
-
- /// <summary>
- /// The client used to communicate with the cache server
- /// </summary>
- protected IRemoteCacheStore Store { get; }
-
- /// <summary>
- /// Gets a value that determines if the backing <see cref="IRemoteCacheStore"/> is connected
- /// to a server
- /// </summary>
- public bool IsConnected => Store.IsConnected;
-
- /// <summary>
- /// Initializes a new <see cref="SessionCacheClient"/>
- /// </summary>
- /// <param name="client"></param>
- /// <param name="maxCacheItems">The maximum number of sessions to keep in memory</param>
- protected SessionCacheClient(IRemoteCacheStore client, int maxCacheItems)
- {
- MaxLoadedEntires = maxCacheItems;
- CacheLock = new();
- CacheTable = new(maxCacheItems);
- Store = client;
- }
-
- private ulong _waitingCount;
-
- /// <summary>
- /// The number of pending connections waiting for results from the cache server
- /// </summary>
- public ulong WaitingConnections => _waitingCount;
-
- /// <summary>
- /// Attempts to get a session from the cache identified by its sessionId asynchronously
- /// </summary>
- /// <param name="entity">The connection/request to attach the session to</param>
- /// <param name="sessionId">The ID of the session to retrieve</param>
- /// <param name="cancellationToken">A token to cancel the operation</param>
- /// <returns>A <see cref="ValueTask"/> that resolves the remote session</returns>
- /// <exception cref="SessionException"></exception>
- public virtual async ValueTask<RemoteSession> GetSessionAsync(IHttpEvent entity, string sessionId, CancellationToken cancellationToken)
- {
- try
- {
- RemoteSession? session;
- //Aquire lock on cache
- lock (CacheLock)
- {
- //See if session is loaded into cache
- if (!CacheTable.TryGetValue(sessionId, out session))
- {
- //Init new record
- session = SessionCtor(sessionId);
- //Add to cache
- CacheTable.Add(session.SessionID, session);
- }
- //Valid entry found in cache
- }
-
- //Inc waiting count
- Interlocked.Increment(ref _waitingCount);
-
- try
- {
- //Load session-data
- await session.WaitAndLoadAsync(entity, cancellationToken);
- return session;
- }
- catch
- {
- //Remove the invalid cached session
- lock (CacheLock)
- {
- _ = CacheTable.Remove(sessionId);
- }
- throw;
- }
- finally
- {
- //Dec waiting count
- Interlocked.Decrement(ref _waitingCount);
- }
- }
- catch (SessionException)
- {
- throw;
- }
- catch (OperationCanceledException)
- {
- throw;
- }
- //Wrap exceptions
- catch (Exception ex)
- {
- throw new SessionException("An unhandled exception was raised", ex);
- }
- }
-
- /// <summary>
- /// Gets a new <see cref="RemoteSession"/> instances for the given sessionId,
- /// and places it a the head of internal cache
- /// </summary>
- /// <param name="sessionId">The session identifier</param>
- /// <returns>The new session for the given ID</returns>
- protected abstract RemoteSession SessionCtor(string sessionId);
-
- /// <summary>
- /// Begins waiting for expired sessions to be evicted from the cache table that
- /// may have pending synchronization operations
- /// </summary>
- /// <param name="log"></param>
- /// <param name="token"></param>
- /// <returns></returns>
- public async Task CleanupExpiredSessionsAsync(ILogProvider log, CancellationToken token)
- {
- while (true)
- {
- try
- {
- //Wait for expired session and dispose it
- using RemoteSession session = await CacheTable.ExpiredSessions.DequeueAsync(token);
-
- //Obtain lock on session
- await session.WaitOneAsync(CancellationToken.None);
-
- log.Verbose("Removed expired session {id}", session.SessionID);
- }
- catch (OperationCanceledException)
- {
- break;
- }
- catch(Exception ex)
- {
- log.Error(ex);
- }
- }
- }
-
- ///<inheritdoc/>
- public void CacheClear()
- {
-
- }
- ///<inheritdoc/>
- public void CacheHardClear()
- {
- //Cleanup cache when disconnected
- lock (CacheLock)
- {
- CacheTable.CacheHardClear();
- }
- }
- }
-}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionDataSerialzer.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionDataSerialzer.cs
new file mode 100644
index 0000000..3af8641
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionDataSerialzer.cs
@@ -0,0 +1,150 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: SessionDataSerialzer.cs
+*
+* SessionDataSerialzer.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+using System.Text;
+using System.Buffers;
+using System.Collections.Generic;
+
+using VNLib.Utils.Memory;
+using VNLib.Utils.Extensions;
+using VNLib.Data.Caching;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+
+ /// <summary>
+ /// Very basic session data serializer memory optimized for key-value
+ /// string pairs
+ /// </summary>
+ internal sealed class SessionDataSerialzer : ICacheObjectSerialzer, ICacheObjectDeserialzer
+ {
+ const string KV_DELIMITER = "\0\0";
+
+ object? ICacheObjectDeserialzer.Deserialze(Type type, ReadOnlySpan<byte> buffer)
+ {
+ if (!type.IsAssignableTo(typeof(IDictionary<string, string>)))
+ {
+ throw new NotSupportedException("This deserialzer only supports IDictionary<string,string>");
+ }
+
+ //Get char count from bin buffer
+ int charCount = Encoding.UTF8.GetCharCount(buffer);
+
+ //Alloc decode buffer
+ using UnsafeMemoryHandle<char> charBuffer = MemoryUtil.UnsafeAllocNearestPage<char>(charCount, true);
+
+ //decode chars
+ Encoding.UTF8.GetChars(buffer, charBuffer.Span);
+
+ //Alloc new dict to write strings to
+ Dictionary<string, string> output = new();
+
+ //Reader to track position of char buffer
+ ForwardOnlyReader<char> reader = new(charBuffer.Span[0..charCount]);
+
+ //Read data from the object data buffer
+ while (reader.WindowSize > 0)
+ {
+ //get index of next separator
+ int sep = GetNextToken(ref reader);
+
+ //No more separators are found, skip
+ if (sep == -1)
+ {
+ break;
+ }
+
+ //Get pointer to key before reading value
+ ReadOnlySpan<char> key = reader.Window[0..sep];
+
+ //Advance reader to next sequence
+ reader.Advance(sep + 2);
+
+ //Find next sepearator to recover the value
+ sep = GetNextToken(ref reader);
+
+ if (sep == -1)
+ {
+ break;
+ }
+
+ //Store value
+ ReadOnlySpan<char> value = reader.Window[0..sep];
+
+ //Set the kvp in the dict
+ output[key.ToString()] = value.ToString();
+
+ //Advance reader again
+ reader.Advance(sep + 2);
+ }
+
+ return output;
+ }
+
+ private static int GetNextToken(ref ForwardOnlyReader<char> reader) => reader.Window.IndexOf(KV_DELIMITER);
+
+ void ICacheObjectSerialzer.Serialize<T>(T obj, IBufferWriter<byte> finiteWriter)
+ {
+ if(obj is not Dictionary<string, string> dict)
+ {
+ throw new NotSupportedException("Data type is not supported by this serializer");
+ }
+
+ //Alloc char buffer, sessions should be under 16k
+ using UnsafeMemoryHandle<char> charBuffer = MemoryUtil.UnsafeAllocNearestPage<char>(16 * 1024);
+
+ using Dictionary<string, string>.Enumerator e = dict.GetEnumerator();
+
+ ForwardOnlyWriter<char> writer = new(charBuffer.Span);
+
+ while (e.MoveNext())
+ {
+ KeyValuePair<string, string> element = e.Current;
+
+ /*
+ * confim there is enough room in the writer, if there is not
+ * flush to the buffer writer
+ */
+ if(element.Key.Length + element.Value.Length + 4 > writer.RemainingSize)
+ {
+ //Flush to the output
+ Encoding.UTF8.GetBytes(writer.AsSpan(), finiteWriter);
+
+ //Reset the writer
+ writer.Reset();
+ }
+
+ //Add key/value elements
+ writer.Append(element.Key);
+ writer.Append(KV_DELIMITER);
+ writer.Append(element.Value);
+ writer.Append(KV_DELIMITER);
+ }
+
+ //encode remaining data
+ Encoding.UTF8.GetBytes(writer.AsSpan(), finiteWriter);
+ }
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionSerializer.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionSerializer.cs
new file mode 100644
index 0000000..8634c39
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionSerializer.cs
@@ -0,0 +1,352 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: SessionSerializer.cs
+*
+* SessionSerializer.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+
+using VNLib.Utils.Memory.Caching;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+ /// <summary>
+ /// Concrete <see cref="ISessionSerialzer{TSession}"/> that provides
+ /// access serialization for session types
+ /// </summary>
+ /// <typeparam name="TSession">The session type</typeparam>
+ public class SessionSerializer<TSession> : ISessionSerialzer<TSession>, ICacheHolder where TSession : IRemoteSession
+ {
+
+ private readonly object StoreLock;
+ private readonly Stack<WaitEntry> _entryPool;
+ private readonly Dictionary<string, WaitEntry> _waitStore;
+ private readonly int MaxPoolSize;
+
+ /// <summary>
+ /// Initializes a new <see cref="SessionSerializer{TSession}"/>
+ /// </summary>
+ /// <param name="poolCapacity">The maximum number of <see cref="WaitEntry"/> elements to pool</param>
+ public SessionSerializer(int poolCapacity)
+ {
+ StoreLock = new();
+ _entryPool = new Stack<WaitEntry>(poolCapacity);
+
+ //Session-ids are security senstive, we must use ordinal(binary) string comparison
+ _waitStore = new Dictionary<string, WaitEntry>(poolCapacity, StringComparer.Ordinal);
+
+ MaxPoolSize = poolCapacity;
+ }
+
+ ///<inheritdoc/>
+ public virtual bool TryGetSession(string sessionId, [NotNullWhen(true)] out TSession? session)
+ {
+ lock (StoreLock)
+ {
+ //Try to see if an entry is loaded, and get the session
+ bool result = _waitStore.TryGetValue(sessionId, out WaitEntry? entry);
+ session = result ? entry!.Session : default;
+ return result;
+ }
+ }
+
+ ///<inheritdoc/>
+ public virtual Task WaitAsync(TSession moniker, CancellationToken cancellation = default)
+ {
+ //Token must not be cancelled
+ cancellation.ThrowIfCancellationRequested();
+
+ WaitEnterToken token;
+
+ lock (StoreLock)
+ {
+ //See if the entry already exists, otherwise get a new wait entry
+ if (!_waitStore.TryGetValue(moniker.SessionID, out WaitEntry? wait))
+ {
+ GetWaitEntry(ref wait, moniker);
+
+ //Add entry to store
+ _waitStore[moniker.SessionID] = wait;
+ }
+
+ //Get waiter before leaving lock
+ token = wait.GetWaiter();
+ }
+
+ return token.EnterWaitAsync(cancellation);
+ }
+
+ ///<inheritdoc/>
+ public virtual void Release(TSession moniker)
+ {
+ /*
+ * When releasing a lock on a moniker, we store entires in an internal table. Wait entires also require mutual
+ * exclustion to properly track waiters. This happens inside a single lock for lower entry times/complexity.
+ * The wait's internal semaphore may also cause longer waits within the lock, so wait entires are "prepared"
+ * by using tokens to access the wait/release mechanisms with proper tracking.
+ *
+ * Tokens can be used to control the wait because the call to release may cause thread yielding (if internal
+ * WaitHandle is being used), so we don't want to block other callers.
+ *
+ * When there are no more waiters for a moniker at the time the lock was entered, the WaitEntry is released
+ * back to the pool.
+ */
+
+ WaitReleaseToken releaser;
+
+ lock (StoreLock)
+ {
+ WaitEntry entry = _waitStore[moniker.SessionID];
+
+ //Call release while holding store lock
+ if(entry.Release(out releaser) == 0)
+ {
+ //No more waiters
+ _waitStore.Remove(moniker.SessionID);
+
+ /*
+ * We must release the semaphore before returning to pool,
+ * its safe because there are no more waiters
+ */
+ releaser.Release();
+
+ ReturnEntry(entry);
+
+ //already released
+ releaser = default;
+ }
+ }
+ //Release sem outside of lock
+ releaser.Release();
+ }
+
+ private void GetWaitEntry([NotNull] ref WaitEntry? wait, TSession session)
+ {
+ //Try to get wait from pool
+ if(!_entryPool.TryPop(out wait))
+ {
+ wait = new();
+ }
+
+ //Init wait with session
+ wait.Prepare(session);
+ }
+
+ private void ReturnEntry(WaitEntry entry)
+ {
+ //Remove session ref
+ entry.Prepare(default);
+
+ if(_entryPool.Count < MaxPoolSize)
+ {
+ _entryPool.Push(entry);
+ }
+ else
+ {
+ //Dispose entry since were not storing it
+ entry.Dispose();
+ }
+ }
+
+ /// <summary>
+ /// NOOP
+ /// </summary>
+ public void CacheClear()
+ { }
+
+ ///<inheritdoc/>
+ public void CacheHardClear()
+ {
+ //Take lock to remove the stored wait entires to dispose of them
+ WaitEntry[] pooled;
+
+ lock (StoreLock)
+ {
+ pooled = _entryPool.ToArray();
+ _entryPool.Clear();
+
+ //Cleanup the wait store
+ _waitStore.TrimExcess(MaxPoolSize);
+ }
+
+ //Dispose entires
+ Array.ForEach(pooled, static pooled => pooled.Dispose());
+ }
+
+ /// <summary>
+ /// An entry within the lock table that
+ /// </summary>
+ protected sealed class WaitEntry : IDisposable
+ {
+ private uint _waitCount;
+ private readonly SemaphoreSlim _waitHandle;
+
+ /// <summary>
+ /// The session this entry is providing mutual exclusion to
+ /// </summary>
+ public TSession? Session { get; private set; }
+
+ /// <summary>
+ /// Initializes a new <see cref="WaitEntry"/>
+ /// </summary>
+ public WaitEntry()
+ {
+ _waitHandle = new(1, 1);
+ Session = default!;
+ }
+
+ /// <summary>
+ /// Gets a token used to enter the lock which may block, or yield async
+ /// outside of a nested lock
+ /// </summary>
+ /// <returns>The waiter used to enter a wait on the moniker</returns>
+ public WaitEnterToken GetWaiter()
+ {
+ /*
+ * Increment wait count before entering the lock
+ * A cancellation is the only way out, so cover that
+ * during the async, only if the token is cancelable
+ */
+ _ = Interlocked.Increment(ref _waitCount);
+ return new(this);
+ }
+
+ /// <summary>
+ /// Prepares a release
+ /// </summary>
+ /// <param name="releaser">
+ /// The token that should be used to release the exclusive lock held on
+ /// a moniker
+ /// </param>
+ /// <returns>The number of remaining waiters</returns>
+ public uint Release(out WaitReleaseToken releaser)
+ {
+ releaser = new(_waitHandle);
+
+ //Decrement release count before leaving
+ return Interlocked.Decrement(ref _waitCount);
+ }
+
+ /// <summary>
+ /// Prepres a new <see cref="WaitEntry"/> for
+ /// its new session.
+ /// </summary>
+ /// <param name="session">The session to hold a referrnce to</param>
+ public void Prepare(TSession? session)
+ {
+ Session = session;
+ _waitCount = 0;
+ }
+
+ /*
+ * Called by WaitEnterToken to enter the lock
+ * outside a nested lock
+ */
+
+ internal Task WaitAsync(CancellationToken cancellation)
+ {
+
+ //See if lock can be entered synchronously
+ if (_waitHandle.Wait(0, CancellationToken.None))
+ {
+ //Lock was entered successfully without async yield
+ return Task.CompletedTask;
+ }
+
+ //Lock must be entered async
+
+ //Check to confirm cancellation may happen
+ if (cancellation.CanBeCanceled)
+ {
+ //Task may be cancelled, so we need to monitor the results to properly set waiting count
+ Task wait = _waitHandle.WaitAsync(cancellation);
+ return WaitForLockEntryWithCancellationAsync(wait);
+ }
+ else
+ {
+ //Task cannot be canceled, so we dont need to monitor the results
+ return _waitHandle.WaitAsync(CancellationToken.None);
+ }
+ }
+
+ private async Task WaitForLockEntryWithCancellationAsync(Task wait)
+ {
+ try
+ {
+ await wait.ConfigureAwait(false);
+ }
+ catch
+ {
+ //Decrement wait count on error entering lock async
+ _ = Interlocked.Decrement(ref _waitCount);
+ throw;
+ }
+ }
+
+ ///<inheritdoc/>
+ public void Dispose()
+ {
+ _waitHandle.Dispose();
+ GC.SuppressFinalize(this);
+ }
+ }
+
+ /// <summary>
+ /// A token used to safely release an exclusive lock inside the
+ /// <see cref="WaitEntry"/>
+ /// </summary>
+ protected readonly ref struct WaitReleaseToken
+ {
+ private readonly SemaphoreSlim? _sem;
+
+ internal WaitReleaseToken(SemaphoreSlim sem) => _sem = sem;
+
+ /// <summary>
+ /// Releases the exclusive lock held by the token. NOTE:
+ /// this method may only be called ONCE after a wait has been
+ /// released
+ /// </summary>
+ public readonly void Release() => _sem?.Release();
+ }
+
+ /// <summary>
+ /// A token used to safely enter a wait for exclusive access to a <see cref="WaitEntry"/>
+ /// </summary>
+ protected readonly ref struct WaitEnterToken
+ {
+ private readonly WaitEntry _entry;
+
+ internal WaitEnterToken(WaitEntry entry) => _entry = entry;
+
+ /// <summary>
+ /// Enters the wait for the WaitEntry. This method may not block
+ /// or yield (IE Return <see cref="Task.CompletedTask"/>)
+ /// </summary>
+ /// <param name="cancellation">A token to cancel the wait for the resource</param>
+ /// <returns></returns>
+ public Task EnterWaitAsync(CancellationToken cancellation) => _entry.WaitAsync(cancellation);
+ }
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionStatus.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionStatus.cs
new file mode 100644
index 0000000..1ab880c
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionStatus.cs
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: SessionStatus.cs
+*
+* SessionStatus.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+ /// <summary>
+ /// Flags for determining the status of an HTTP session
+ /// before it is releases/post processed
+ /// </summary>
+ [Flags]
+ public enum SessionStatus
+ {
+ /// <summary>
+ /// The session has not been modified and does not need attention
+ /// </summary>
+ None = 0,
+ /// <summary>
+ /// The session is no longer valid and should be deleted
+ /// </summary>
+ Delete = 1,
+ /// <summary>
+ /// The session has been modified and requires its data be published
+ /// </summary>
+ UpdateOnly = 2,
+ /// <summary>
+ /// The session has been modified and requires an ID change
+ /// </summary>
+ RegenId = 4
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionStore.cs b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionStore.cs
new file mode 100644
index 0000000..62de219
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.Cache.Client/src/SessionStore.cs
@@ -0,0 +1,312 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Sessions.Cache.Client
+* File: SessionStore.cs
+*
+* SessionStore.cs is part of VNLib.Plugins.Sessions.Cache.Client which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Sessions.Cache.Client is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Sessions.Cache.Client is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+using VNLib.Net.Http;
+using VNLib.Utils.Logging;
+using VNLib.Data.Caching.Exceptions;
+using VNLib.Plugins.Essentials.Sessions;
+using VNLib.Plugins.Sessions.Cache.Client.Exceptions;
+
+namespace VNLib.Plugins.Sessions.Cache.Client
+{
+
+ /// <summary>
+ /// Provides an abstract <see cref="ISessionStore{TSession}"/> for managing sessions for HTTP connections
+ /// remote cache backed sessions
+ /// </summary>
+ /// <typeparam name="TSession"></typeparam>
+ public abstract class SessionStore<TSession> : ISessionStore<TSession> where TSession: IRemoteSession
+ {
+#nullable disable
+
+ /*
+ * Default imple for serializer
+ */
+ protected virtual ISessionSerialzer<TSession> Serializer { get; } = new SessionSerializer<TSession>(100);
+
+ /// <summary>
+ /// The <see cref="ISessionIdFactory"/> that provides session ids for connections
+ /// </summary>
+ protected abstract ISessionIdFactory IdFactory { get; }
+ /// <summary>
+ /// The backing cache store
+ /// </summary>
+ protected abstract IRemoteCacheStore Cache { get; }
+ /// <summary>
+ /// The session factory, produces sessions from their initial data and session-id
+ /// </summary>
+ protected abstract ISessionFactory<TSession> SessionFactory { get; }
+ /// <summary>
+ /// The log provider for writing background update exceptions to
+ /// </summary>
+ protected abstract ILogProvider Log { get; }
+
+#nullable enable
+
+ ///<inheritdoc/>
+ public virtual async ValueTask<TSession?> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
+ {
+ //Wrap exceptions in session exceptions
+ try
+ {
+ if (!IdFactory.CanService(entity))
+ {
+ return default;
+ }
+
+ //Get the session id from the entity
+ string? sessionId = IdFactory.TryGetSessionId(entity);
+
+ //If regeneration is not supported, return since id is null
+ if (sessionId == null && !IdFactory.RegenerationSupported)
+ {
+ return default;
+ }
+
+ if (sessionId == null)
+ {
+ //Get new sessionid
+ sessionId = IdFactory.RegenerateId(entity);
+
+ //Create a new session
+ TSession? session = SessionFactory.GetNewSession(entity, sessionId, null);
+
+ if (session != null)
+ {
+ //Enter wait for the new session, this call should not block or yield
+ await Serializer.WaitAsync(session, cancellationToken);
+ }
+
+ return session;
+ }
+ else
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ Dictionary<string, string>? sessionData = null;
+
+ //See if the session is currently in use, if so wait for access to it
+ if (Serializer.TryGetSession(sessionId, out TSession? activeSession))
+ {
+ //reuse the session
+ await Serializer.WaitAsync(activeSession, cancellationToken);
+
+ //after wait has been completed, check the status of the session
+ if (activeSession.IsValid(out Exception? cause))
+ {
+ //Session is valid, we can use it
+ return activeSession;
+ }
+
+ //release the wait, no use for the session in invalid state
+ Serializer.Release(activeSession);
+
+ //Rethrow exception that cause invalidation
+ if (cause != null)
+ {
+ throw cause;
+ }
+
+ //Regen id and continue loading
+ }
+ else
+ {
+ //Session cannot be found local, so we need to retrieve it from cache
+ sessionData = await Cache.GetObjectAsync<Dictionary<string, string>>(sessionId, cancellationToken);
+ }
+
+
+ //If the cache entry is null, we may choose to regenrate the session id
+ if (sessionData == null && IdFactory.RegenIdOnEmptyEntry)
+ {
+ sessionId = IdFactory.RegenerateId(entity);
+ }
+
+ //Create a new session
+ TSession? session = SessionFactory.GetNewSession(entity, sessionId, sessionData);
+
+ if(session != null)
+ {
+ //Enter wait for the new session
+ await Serializer.WaitAsync(session, cancellationToken);
+ }
+
+ return session;
+ }
+ }
+ catch(OperationCanceledException)
+ {
+ throw;
+ }
+ catch (TimeoutException)
+ {
+ throw;
+ }
+ catch (SessionException)
+ {
+ throw;
+ }
+ catch(Exception ex)
+ {
+ throw new SessionException("An exception occured during session processing", ex);
+ }
+ }
+
+ ///<inheritdoc/>
+ public virtual ValueTask ReleaseSessionAsync(TSession session, IHttpEvent entity)
+ {
+ //Get status on release
+ SessionStatus status = session.GetStatus();
+
+ //confirm the cache client is connected
+ if(status != SessionStatus.None && !Cache.IsConnected)
+ {
+ throw new SessionUpdateFailedException("The required session operation cannot be completed because the cache is not connected");
+ }
+
+ //Delete status is required
+ if (status.HasFlag(SessionStatus.Delete))
+ {
+ //Delete the session
+ _ = DeleteSessionAsync(session);
+ }
+ else if (status.HasFlag(SessionStatus.RegenId))
+ {
+ if (!IdFactory.RegenerationSupported)
+ {
+ throw new SessionException("Session id regeneration is not supported by this store");
+ }
+
+ //Get new id for session
+ string newId = IdFactory.RegenerateId(entity);
+
+ //Update data and id
+ _ = UpdateSessionAndIdAsync(session, newId);
+ }
+ else if (status.HasFlag(SessionStatus.UpdateOnly))
+ {
+ //Just run update
+ _ = UpdateSessionAndIdAsync(session, null);
+ }
+ else
+ {
+ //Always release the session after update
+ Serializer.Release(session);
+ }
+
+ return ValueTask.CompletedTask;
+ }
+
+ /// <summary>
+ /// Updates a mondified session on release, and optionally updates
+ /// its id
+ /// </summary>
+ /// <param name="session"></param>
+ /// <param name="newId">The session's new id</param>
+ /// <returns>A task that completes when the session update is complete</returns>
+ /// <remarks>
+ /// Unless overridden
+ /// </remarks>
+ protected virtual async Task UpdateSessionAndIdAsync(TSession session, string? newId)
+ {
+ try
+ {
+ //Get the session's data
+ IDictionary<string, string> sessionData = session.GetSessionData();
+
+ //Update the session's data async
+ await Cache.AddOrUpdateObjectAsync(session.SessionID, newId, sessionData);
+
+
+ /*
+ * If the session id changes, the old sesion can be invalidated
+ * and the session will be recovered from cache on load
+ */
+
+ if(sessionData != null)
+ {
+ session.Destroy(null);
+ }
+ else
+ {
+ session.SessionUpdateComplete();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Error("Exception raised during session update, ID {id} NewID {nid}\n{ex}", session.SessionID, newId, ex);
+
+ //Destroy the session with an error
+ session.Destroy(ex);
+ }
+ finally
+ {
+ //Always release the session after update
+ Serializer.Release(session);
+ }
+ }
+
+ /// <summary>
+ /// Delets a session when the session has the <see cref="SessionStatus.Delete"/>
+ /// flag set
+ /// </summary>
+ /// <param name="session">The session to delete</param>
+ /// <returns>A task that completes when the session is destroyed</returns>
+ protected virtual async Task DeleteSessionAsync(TSession session)
+ {
+ try
+ {
+ //Update the session's data async
+ await Cache.DeleteObjectAsync(session.SessionID);
+
+ //Destroy the session
+ session.Destroy(null);
+ }
+ catch(ObjectNotFoundException)
+ {
+ //ingore onfe, if the session does not exist in cache
+
+ //Destroy the session
+ session.Destroy(null);
+ }
+ catch (Exception ex)
+ {
+ Log.Error("Exception raised during session delete, ID {id}\n{ex}", session.SessionID, ex);
+
+ //Destroy the session with an error
+ session.Destroy(ex);
+ }
+ finally
+ {
+ //Release the session now that delete has been set
+ Serializer.Release(session);
+ }
+ }
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.Memory/LICENSE.txt b/libs/VNLib.Plugins.Sessions.Memory/LICENSE.txt
deleted file mode 100644
index 147bcd6..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/LICENSE.txt
+++ /dev/null
@@ -1,195 +0,0 @@
-Copyright (c) 2022 Vaughn Nugent
-
-Contact information
- Name: Vaughn Nugent
- Email: public[at]vaughnnugent[dot]com
- Website: https://www.vaughnnugent.com
-
-The software in this repository is licensed under the GNU Affero GPL version 3.0 (or any later version).
-
-GNU AFFERO GENERAL PUBLIC LICENSE
-
-Version 3, 19 November 2007
-
-Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
-Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
-Preamble
-
-The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
-
-The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
-
-When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
-
-Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
-
-A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
-
-The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
-
-An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
-
-The precise terms and conditions for copying, distribution and modification follow.
-TERMS AND CONDITIONS
-0. Definitions.
-
-"This License" refers to version 3 of the GNU Affero General Public License.
-
-"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
-
-"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
-
-To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
-
-A "covered work" means either the unmodified Program or a work based on the Program.
-
-To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
-
-To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
-
-An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
-1. Source Code.
-
-The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
-
-A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
-
-The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
-
-The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
-
-The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
-
-The Corresponding Source for a work in source code form is that same work.
-2. Basic Permissions.
-
-All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
-
-You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
-
-Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
-3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
-No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
-
-When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
-4. Conveying Verbatim Copies.
-
-You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
-
-You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
-5. Conveying Modified Source Versions.
-
-You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
- c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
-
-A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
-6. Conveying Non-Source Forms.
-
-You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
- d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
-
-A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
-
-A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
-
-"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
-
-If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
-
-The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
-
-Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
-7. Additional Terms.
-
-"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
-
-When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
-
-Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
- e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
-
-All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
-
-If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
-
-Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
-8. Termination.
-
-You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
-
-However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
-
-Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
-
-Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
-9. Acceptance Not Required for Having Copies.
-
-You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
-10. Automatic Licensing of Downstream Recipients.
-
-Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
-
-An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
-
-You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
-11. Patents.
-
-A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
-
-A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
-
-Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
-
-In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
-
-If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
-
-If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
-
-A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
-
-Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
-12. No Surrender of Others' Freedom.
-
-If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
-13. Remote Network Interaction; Use with the GNU General Public License.
-
-Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
-
-Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
-14. Revised Versions of this License.
-
-The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
-
-If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
-
-Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
-15. Disclaimer of Warranty.
-
-THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-16. Limitation of Liability.
-
-IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-17. Interpretation of Sections 15 and 16.
-
-If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
-
-END OF TERMS AND CONDITIONS \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.Memory/README.md b/libs/VNLib.Plugins.Sessions.Memory/README.md
deleted file mode 100644
index 2e78c1f..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/README.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# VNLib.Plugins.Sessions.Memory
-*A memory-backed, self-contained, session provider, that may be loaded directly as a plugin or supports dynamic loading with multiple providers*
-
-#### Builds
-Debug build w/ symbols & xml docs, release builds, NuGet packages, and individually packaged source code are available on my [website](https://www.vaughnnugent.com/resources/software). All tar-gzip (.tgz) files will have an associated .sha384 appended checksum of the desired download file.
-
-## Notes
-When dynamically loading as a sesstion provider, since this plugin provides Web based sessions, it should be a lower priority than an OAuth2 session provider, because it attempts to attach sessions to all applicable connections, potentially bypassing an OAuth2 session.
-
-## License
-Source files in for this project are licensed to you under the GNU Affero General Public License (or any later version). See the LICENSE files for more information. \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.Memory/build.readme.md b/libs/VNLib.Plugins.Sessions.Memory/build.readme.md
deleted file mode 100644
index e69de29..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/build.readme.md
+++ /dev/null
diff --git a/libs/VNLib.Plugins.Sessions.Memory/src/MemSessionPluginEntry.cs b/libs/VNLib.Plugins.Sessions.Memory/src/MemSessionPluginEntry.cs
deleted file mode 100644
index 0374243..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/src/MemSessionPluginEntry.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Sessions.Memory
-* File: MemSessionPluginEntry.cs
-*
-* MemSessionPluginEntry.cs is part of VNLib.Plugins.Sessions.Memory which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Sessions.Memory is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Sessions.Memory is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-
-using VNLib.Net.Http;
-using VNLib.Utils.Logging;
-using VNLib.Plugins.Essentials.Sessions;
-
-namespace VNLib.Plugins.Sessions.Memory
-{
- /// <summary>
- /// Provides an IPlugin entrypoint for standalone memory sessions
- /// </summary>
- public sealed class MemSessionPluginEntry : PluginBase, ISessionProvider
- {
- ///<inheritdoc/>
- public override string PluginName => "Essentials.MemorySessions";
-
- private readonly MemorySessionEntrypoint ep = new();
-
- ///<inheritdoc/>
- protected override void OnLoad()
- {
- //Try to load
- ep.Load(this, Log);
- Log.Information("Plugin loaded");
- }
-
- ///<inheritdoc/>
- protected override void OnUnLoad()
- {
- Log.Information("Plugin unloaded");
- }
-
- ///<inheritdoc/>
- protected override void ProcessHostCommand(string cmd)
- {
- throw new NotImplementedException();
- }
-
- ///<inheritdoc/>
- public ValueTask<SessionHandle> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
- {
- return ep.GetSessionAsync(entity, cancellationToken);
- }
- }
-}
diff --git a/libs/VNLib.Plugins.Sessions.Memory/src/MemorySession.cs b/libs/VNLib.Plugins.Sessions.Memory/src/MemorySession.cs
deleted file mode 100644
index 5033362..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/src/MemorySession.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Essentials.Sessions.Memory
-* File: MemorySession.cs
-*
-* MemorySession.cs is part of VNLib.Plugins.Essentials.Sessions.Memory which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-using System.Net;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-using VNLib.Plugins.Essentials.Extensions;
-
-using VNLib.Utils.Async;
-using VNLib.Net.Http;
-using VNLib.Utils.Memory.Caching;
-using VNLib.Plugins.Essentials.Sessions;
-using static VNLib.Plugins.Essentials.Sessions.ISessionExtensions;
-
-namespace VNLib.Plugins.Sessions.Memory
-{
- internal class MemorySession : SessionBase, ICacheable
- {
- private readonly Dictionary<string, string> DataStorage;
-
- private readonly Func<IHttpEvent, string, string> OnSessionUpdate;
- private readonly AsyncQueue<MemorySession> ExpiredTable;
-
- public MemorySession(string sessionId, IPAddress ipAddress, Func<IHttpEvent, string, string> onSessionUpdate, AsyncQueue<MemorySession> expired)
- {
- //Set the initial is-new flag
- DataStorage = new Dictionary<string, string>(10);
- ExpiredTable = expired;
-
- OnSessionUpdate = onSessionUpdate;
- //Get new session id
- SessionID = sessionId;
- UserIP = ipAddress;
- SessionType = SessionType.Web;
- Created = DateTimeOffset.UtcNow;
- //Init
- IsNew = true;
- }
- //Store in memory directly
- public override IPAddress UserIP { get; protected set; }
-
- //Session type has no backing store, so safe to hard-code it's always web
-
- public override SessionType SessionType => SessionType.Web;
-
- protected override ValueTask<Task?> UpdateResource(bool isAsync, IHttpEvent state)
- {
- //if invalid is set, invalide the current session
- if (Flags.IsSet(INVALID_MSK))
- {
- //Clear storage, and regenerate the sessionid
- DataStorage.Clear();
- //store new sessionid
- SessionID = OnSessionUpdate(state, SessionID);
- //Reset ip-address
- UserIP = state.Server.GetTrustedIp();
- //Update created-time
- Created = DateTimeOffset.UtcNow;
- //Re-initialize the session to the state of the current connection
- this.InitNewSession(state.Server);
- //Modified flag doesnt matter since there is no write-back
-
- }
- else if (Flags.IsSet(REGEN_ID_MSK))
- {
- //Regen id without modifying the data store
- SessionID = OnSessionUpdate(state, SessionID);
- }
- //Clear flags
- Flags.ClearAll();
- //Memory session always completes
- return ValueTask.FromResult<Task?>(null);
- }
-
- protected override string IndexerGet(string key)
- {
- return DataStorage.GetValueOrDefault(key, string.Empty);
- }
-
- protected override void IndexerSet(string key, string value)
- {
- //Check for special keys
- switch (key)
- {
- //For token/login hashes, we can set the upgrade flag
- case LOGIN_TOKEN_ENTRY:
- case TOKEN_ENTRY:
- Flags.Set(REGEN_ID_MSK);
- break;
- }
- DataStorage[key] = value;
- }
-
-
- DateTime ICacheable.Expires { get; set; }
-
- void ICacheable.Evicted()
- {
- DataStorage.Clear();
- //Enque cleanup
- _ = ExpiredTable.TryEnque(this);
- }
-
- bool IEquatable<ICacheable>.Equals(ICacheable? other) => other is ISession ses && SessionID.Equals(ses.SessionID, StringComparison.Ordinal);
-
- }
-}
diff --git a/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionConfig.cs b/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionConfig.cs
deleted file mode 100644
index b330bb1..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionConfig.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Essentials.Sessions.Memory
-* File: MemorySessionConfig.cs
-*
-* MemorySessionConfig.cs is part of VNLib.Plugins.Essentials.Sessions.Memory which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-
-using VNLib.Utils.Logging;
-
-namespace VNLib.Plugins.Sessions.Memory
-{
- /// <summary>
- /// Represents configration variables used to create and operate http sessions.
- /// </summary>
- public readonly struct MemorySessionConfig
- {
- /// <summary>
- /// The name of the cookie to use for matching sessions
- /// </summary>
- public string SessionCookieID { get; init; }
- /// <summary>
- /// The size (in bytes) of the genreated SessionIds
- /// </summary>
- public uint SessionIdSizeBytes { get; init; }
- /// <summary>
- /// The amount of time a session is valid (within the backing store)
- /// </summary>
- public TimeSpan SessionTimeout { get; init; }
- /// <summary>
- /// The log for which all errors within the <see cref="SessionProvider"/> instance will be written to.
- /// </summary>
- public ILogProvider SessionLog { get; init; }
- /// <summary>
- /// The maximum number of sessions allowed to be cached in memory. If this value is exceed requests to this
- /// server will be denied with a 503 error code
- /// </summary>
- public int MaxAllowedSessions { get; init; }
- }
-} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionEntrypoint.cs b/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionEntrypoint.cs
deleted file mode 100644
index 6cd25ab..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionEntrypoint.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Essentials.Sessions.Memory
-* File: MemorySessionEntrypoint.cs
-*
-* MemorySessionEntrypoint.cs is part of VNLib.Plugins.Essentials.Sessions.Memory which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-using System.Text.Json;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-
-using VNLib.Net.Http;
-using VNLib.Utils.Logging;
-using VNLib.Utils.Extensions;
-using VNLib.Plugins.Essentials.Sessions;
-using VNLib.Plugins.Extensions.Loading.Events;
-using VNLib.Plugins.Extensions.Loading;
-
-namespace VNLib.Plugins.Sessions.Memory
-{
-
- /// <summary>
- /// Dynamically loadable session provider
- /// </summary>
- public sealed class MemorySessionEntrypoint : ISessionProvider, IIntervalScheduleable
- {
- const string WEB_SESSION_CONFIG = "web";
-
- private MemorySessionStore? _sessions;
-
- public bool CanProcess(IHttpEvent entity)
- {
- //Web sessions can always be provided
- return _sessions != null;
- }
-
- public ValueTask<SessionHandle> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
- {
- return _sessions!.GetSessionAsync(entity, cancellationToken);
- }
-
- public void Load(PluginBase plugin, ILogProvider localized)
- {
- //Get websessions config element
-
- IReadOnlyDictionary<string, JsonElement> webSessionConfig = plugin.GetConfig(WEB_SESSION_CONFIG);
-
- MemorySessionConfig config = new()
- {
- SessionLog = localized,
- MaxAllowedSessions = webSessionConfig["cache_size"].GetInt32(),
- SessionIdSizeBytes = webSessionConfig["cookie_size"].GetUInt32(),
- SessionTimeout = webSessionConfig["valid_for_sec"].GetTimeSpan(TimeParseType.Seconds),
- SessionCookieID = webSessionConfig["cookie_name"].GetString() ?? throw new KeyNotFoundException($"Missing required element 'cookie_name' for config '{WEB_SESSION_CONFIG}'"),
- };
-
- _sessions = new(config);
-
- //Begin listening for expired records
- _ = plugin.ObserveTask(() => _sessions.CleanupExiredAsync(localized, plugin.UnloadToken));
-
- //Schedule garbage collector
- plugin.ScheduleInterval(this, TimeSpan.FromMinutes(1));
-
- //Call cleanup on exit
- _ = plugin.RegisterForUnload(_sessions.Cleanup);
- }
-
- Task IIntervalScheduleable.OnIntervalAsync(ILogProvider log, CancellationToken cancellationToken)
- {
- //Cleanup expired sessions on interval
- _sessions?.GC();
- return Task.CompletedTask;
- }
- }
-}
diff --git a/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionStore.cs b/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionStore.cs
deleted file mode 100644
index 774681a..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/src/MemorySessionStore.cs
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Essentials.Sessions.Memory
-* File: MemorySessionStore.cs
-*
-* MemorySessionStore.cs is part of VNLib.Plugins.Essentials.Sessions.Memory which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-
-using VNLib.Net.Http;
-using VNLib.Net.Http.Core;
-using VNLib.Utils;
-using VNLib.Utils.Async;
-using VNLib.Utils.Logging;
-using VNLib.Utils.Extensions;
-using VNLib.Plugins.Essentials;
-using VNLib.Plugins.Essentials.Sessions;
-using VNLib.Plugins.Essentials.Extensions;
-
-namespace VNLib.Plugins.Sessions.Memory
-{
- /// <summary>
- /// An <see cref="ISessionProvider"/> for in-process-memory backed sessions
- /// </summary>
- internal sealed class MemorySessionStore : ISessionProvider
- {
- private readonly Dictionary<string, MemorySession> SessionsStore;
-
- internal readonly MemorySessionConfig Config;
- internal readonly SessionIdFactory IdFactory;
- internal readonly AsyncQueue<MemorySession> ExpiredSessions;
-
- public MemorySessionStore(MemorySessionConfig config)
- {
- Config = config;
- SessionsStore = new(config.MaxAllowedSessions, StringComparer.Ordinal);
- IdFactory = new(config.SessionIdSizeBytes, config.SessionCookieID, config.SessionTimeout);
- ExpiredSessions = new(false, true);
- }
-
- ///<inheritdoc/>
- public async ValueTask<SessionHandle> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
- {
-
- static ValueTask SessionHandleClosedAsync(ISession session, IHttpEvent ev)
- {
- return (session as MemorySession)!.UpdateAndRelease(true, ev);
- }
-
- //Try to get the id for the session
- if (IdFactory.TryGetSessionId(entity, out string? sessionId))
- {
- //Try to get the old record or evict it
- ERRNO result = SessionsStore.TryGetOrEvictRecord(sessionId, out MemorySession? session);
- if(result > 0)
- {
- //Valid, now wait for exclusive access
- await session.WaitOneAsync(cancellationToken);
- return new (session, SessionHandleClosedAsync);
- }
- else
- {
- //try to cleanup expired records
- GC();
- //Make sure there is enough room to add a new session
- if (SessionsStore.Count >= Config.MaxAllowedSessions)
- {
- entity.Server.SetNoCache();
- //Set 503 when full
- entity.CloseResponse(System.Net.HttpStatusCode.ServiceUnavailable);
- //Cannot service new session
- return new(null, FileProcessArgs.VirtualSkip, null);
- }
- //Initialze a new session
- session = new(sessionId, entity.Server.GetTrustedIp(), UpdateSessionId, ExpiredSessions);
- //Increment the semaphore
- (session as IWaitHandle).WaitOne();
- //store the session in cache while holding semaphore, and set its expiration
- SessionsStore.StoreRecord(session.SessionID, session, Config.SessionTimeout);
- //Init new session handle
- return new (session, SessionHandleClosedAsync);
- }
- }
- else
- {
- return SessionHandle.Empty;
- }
- }
-
- public async Task CleanupExiredAsync(ILogProvider log, CancellationToken token)
- {
- while (true)
- {
- try
- {
- //Wait for expired session and dispose it
- using MemorySession session = await ExpiredSessions.DequeueAsync(token);
-
- //Obtain lock on session
- await session.WaitOneAsync(CancellationToken.None);
-
- log.Verbose("Removed expired session {id}", session.SessionID);
- }
- catch (OperationCanceledException)
- {
- break;
- }
- catch (Exception ex)
- {
- log.Error(ex);
- }
- }
- }
-
- private string UpdateSessionId(IHttpEvent entity, string oldId)
- {
- //Generate and set a new sessionid
- string newid = IdFactory.GenerateSessionId(entity);
- //Aquire lock on cache
- lock (SessionsStore)
- {
- //Change the cache lookup id
- if (SessionsStore.Remove(oldId, out MemorySession? session))
- {
- SessionsStore.Add(newid, session);
- }
- }
- return newid;
- }
-
- /// <summary>
- /// Evicts all sessions from the current store
- /// </summary>
- public void Cleanup()
- {
- //Expire all old records to cleanup all entires
- this.SessionsStore.CollectRecords(DateTime.MaxValue);
- }
- /// <summary>
- /// Collects all expired records from the current store
- /// </summary>
- public void GC()
- {
- //collect expired records
- this.SessionsStore.CollectRecords();
- }
- }
-}
diff --git a/libs/VNLib.Plugins.Sessions.Memory/src/SessionIdFactory.cs b/libs/VNLib.Plugins.Sessions.Memory/src/SessionIdFactory.cs
deleted file mode 100644
index 253fa81..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/src/SessionIdFactory.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Essentials.Sessions.Memory
-* File: SessionIdFactory.cs
-*
-* SessionIdFactory.cs is part of VNLib.Plugins.Essentials.Sessions.Memory which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Essentials.Sessions.Memory is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-using System.Diagnostics.CodeAnalysis;
-
-using VNLib.Hashing;
-using VNLib.Net.Http;
-using VNLib.Plugins.Essentials.Extensions;
-
-namespace VNLib.Plugins.Sessions.Memory
-{
- internal sealed class SessionIdFactory
- {
- private readonly int IdSize;
- private readonly string cookieName;
- private readonly TimeSpan ValidFor;
-
- public SessionIdFactory(uint idSize, string cookieName, TimeSpan validFor)
- {
- IdSize = (int)idSize;
- this.cookieName = cookieName;
- ValidFor = validFor;
- }
-
- public string GenerateSessionId(IHttpEvent entity)
- {
- //Random hex hash
- string cookie = RandomHash.GetRandomBase32(IdSize);
-
- //Set the session id cookie
- entity.Server.SetCookie(cookieName, cookie, ValidFor, secure: true, httpOnly: true);
-
- //return session-id value from cookie value
- return cookie;
- }
-
- public bool TryGetSessionId(IHttpEvent entity, [NotNullWhen(true)] out string? sessionId)
- {
- //Get authorization token and make sure its not too large to cause a buffer overflow
- if (entity.Server.GetCookie(cookieName, out sessionId))
- {
- return true;
- }
- //Only add sessions for user-agents
- else if (entity.Server.IsBrowser())
- {
- //Get a new session id
- sessionId = GenerateSessionId(entity);
-
- return true;
- }
- else
- {
- sessionId = null;
- return false;
- }
- }
- }
-}
diff --git a/libs/VNLib.Plugins.Sessions.Memory/src/VNLib.Plugins.Sessions.Memory.csproj b/libs/VNLib.Plugins.Sessions.Memory/src/VNLib.Plugins.Sessions.Memory.csproj
deleted file mode 100644
index cfffe28..0000000
--- a/libs/VNLib.Plugins.Sessions.Memory/src/VNLib.Plugins.Sessions.Memory.csproj
+++ /dev/null
@@ -1,49 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <Nullable>enable</Nullable>
- <TargetFramework>net6.0</TargetFramework>
- <AssemblyName>VNLib.Plugins.Sessions.Memory</AssemblyName>
- <RootNamespace>VNLib.Plugins.Sessions.Memory</RootNamespace>
- <SignAssembly>True</SignAssembly>
- <AssemblyOriginatorKeyFile>\\vaughnnugent.com\Internal\Folder Redirection\vman\Documents\Programming\Software\StrongNameingKey.snk</AssemblyOriginatorKeyFile>
- <GenerateDocumentationFile>True</GenerateDocumentationFile>
- <AnalysisLevel>latest-all</AnalysisLevel>
- <EnableDynamicLoading>true</EnableDynamicLoading>
- </PropertyGroup>
-
- <PropertyGroup>
- <Authors>Vaughn Nugent</Authors>
- <Copyright>Copyright © 2023 Vaughn Nugent</Copyright>
- <PackageProjectUrl>https://www.vaughnugent.com/resources/software</PackageProjectUrl>
- </PropertyGroup>
-
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
- <Deterministic>False</Deterministic>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
- <Deterministic>False</Deterministic>
- </PropertyGroup>
-
- <ProjectExtensions><VisualStudio><UserProperties /></VisualStudio></ProjectExtensions>
- <ItemGroup>
- <PackageReference Include="ErrorProne.NET.CoreAnalyzers" Version="0.1.2">
- <PrivateAssets>all</PrivateAssets>
- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
- </PackageReference>
- <PackageReference Include="ErrorProne.NET.Structs" Version="0.1.2">
- <PrivateAssets>all</PrivateAssets>
- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
- </PackageReference>
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\..\..\..\..\core\lib\Plugins.Essentials\src\VNLib.Plugins.Essentials.csproj" />
- <ProjectReference Include="..\..\..\..\..\core\lib\Utils\src\VNLib.Utils.csproj" />
- <ProjectReference Include="..\..\..\..\Extensions\lib\VNLib.Plugins.Extensions.Loading\src\VNLib.Plugins.Extensions.Loading.csproj" />
- </ItemGroup>
-
- <Target Condition="'$(BuildingInsideVisualStudio)' == true" Name="PostBuild" AfterTargets="PostBuildEvent">
- <Exec Command="start xcopy &quot;$(TargetDir)&quot; &quot;..\..\..\..\..\devplugins\RuntimeAssets\$(TargetName)&quot; /E /Y /R" />
- </Target>
-
-</Project>
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/AccessTokenEndpoint.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/AccessTokenEndpoint.cs
index f01b764..9f0f35d 100644
--- a/libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/AccessTokenEndpoint.cs
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/AccessTokenEndpoint.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.OAuth
@@ -25,7 +25,6 @@
using System;
using System.Net;
using System.Text.Json;
-using System.Threading;
using System.Threading.Tasks;
using VNLib.Utils.Memory;
@@ -42,17 +41,16 @@ using VNLib.Plugins.Extensions.Validation;
namespace VNLib.Plugins.Sessions.OAuth.Endpoints
{
- delegate Task<IOAuth2TokenResult?> CreateTokenImpl(HttpEntity ev, UserApplication application, CancellationToken cancellation = default);
/// <summary>
/// Grants authorization to OAuth2 clients to protected resources
/// with access tokens
/// </summary>
+ [ConfigurationName(O2SessionProviderEntry.OAUTH2_CONFIG_KEY)]
internal sealed class AccessTokenEndpoint : ResourceEndpointBase
{
- private readonly CreateTokenImpl CreateToken;
+ private readonly IApplicationTokenFactory TokenFactory;
private readonly ApplicationStore Applications;
-
private readonly Task<ReadOnlyJsonWebKey?> JWTVerificationKey;
//override protection settings to allow most connections to authenticate
@@ -63,11 +61,17 @@ namespace VNLib.Plugins.Sessions.OAuth.Endpoints
DisableVerifySessionCors = true
};
- public AccessTokenEndpoint(string path, PluginBase pbase, CreateTokenImpl tokenStore)
+ public AccessTokenEndpoint(PluginBase pbase, IConfigScope config)
{
+ string? path = config["token_path"].GetString();;
+
InitPathAndLog(path, pbase.Log);
- CreateToken = tokenStore;
+
+ //Get the session provider, as its a token factory
+ TokenFactory = pbase.GetOrCreateSingleton<OAuth2SessionProvider>();
+
Applications = new(pbase.GetContextOptions(), pbase.GetPasswords());
+
//Try to get the application token key for verifying signed application JWTs
JWTVerificationKey = pbase.TryGetSecretAsync("application_token_key").ToJsonWebKey();
}
@@ -172,7 +176,7 @@ namespace VNLib.Plugins.Sessions.OAuth.Endpoints
return VfReturnType.VirtualSkip;
}
- IOAuth2TokenResult? result = await CreateToken(entity, app, entity.EventCancellation);
+ IOAuth2TokenResult? result = await TokenFactory.CreateAccessTokenAsync(entity, app, entity.EventCancellation);
if (result == null)
{
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/RevocationEndpoint.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/RevocationEndpoint.cs
index 81f82c2..45a8391 100644
--- a/libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/RevocationEndpoint.cs
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/Endpoints/RevocationEndpoint.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.OAuth
@@ -22,10 +22,6 @@
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
-using System;
-using System.Text.Json;
-using System.Collections.Generic;
-
using VNLib.Plugins.Essentials;
using VNLib.Plugins.Essentials.Oauth;
using VNLib.Plugins.Extensions.Loading;
@@ -40,7 +36,7 @@ namespace VNLib.Plugins.Sessions.OAuth.Endpoints
internal class RevocationEndpoint : O2EndpointBase
{
- public RevocationEndpoint(PluginBase pbase, IReadOnlyDictionary<string, JsonElement> config)
+ public RevocationEndpoint(PluginBase pbase, IConfigScope config)
{
string? path = config["path"].GetString();
InitPathAndLog(path, pbase.Log);
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/GetTokenResult.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/GetTokenResult.cs
new file mode 100644
index 0000000..0587931
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/GetTokenResult.cs
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Essentials.Sessions.OAuth
+* File: GetTokenResult.cs
+*
+* GetTokenResult.cs is part of VNLib.Plugins.Essentials.Sessions.OAuth which is
+* part of the larger VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+
+namespace VNLib.Plugins.Sessions.OAuth
+{
+
+ /// <summary>
+ /// The result of generating a new access token
+ /// </summary>
+ /// <param name="AccessToken">The new access token</param>
+ /// <param name="RefreshToken">The optional refresh token</param>
+ public readonly record struct GetTokenResult(string AccessToken, string? RefreshToken)
+ { }
+}
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/TokenAndSessionIdResult.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/IApplicationTokenFactory.cs
index 6ae2af4..7f65ec3 100644
--- a/libs/VNLib.Plugins.Sessions.OAuth/src/TokenAndSessionIdResult.cs
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/IApplicationTokenFactory.cs
@@ -1,11 +1,11 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.OAuth
-* File: TokenAndSessionIdResult.cs
+* File: IApplicationTokenFactory.cs
*
-* TokenAndSessionIdResult.cs is part of VNLib.Plugins.Essentials.Sessions.OAuth which is part of the larger
+* IApplicationTokenFactory.cs is part of VNLib.Plugins.Essentials.Sessions.OAuth which is part of the larger
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials.Sessions.OAuth is free software: you can redistribute it and/or modify
@@ -22,20 +22,17 @@
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
+using System.Threading;
+using System.Threading.Tasks;
+
+using VNLib.Net.Http;
+using VNLib.Plugins.Essentials.Oauth.Tokens;
+using VNLib.Plugins.Essentials.Oauth.Applications;
namespace VNLib.Plugins.Sessions.OAuth
{
- public readonly struct TokenAndSessionIdResult
+ interface IApplicationTokenFactory
{
- public readonly string SessionId;
- public readonly string AccessToken;
- public readonly string? RefreshToken;
-
- public TokenAndSessionIdResult(string sessionId, string token, string? refreshToken)
- {
- SessionId = sessionId;
- AccessToken = token;
- RefreshToken = refreshToken;
- }
+ Task<IOAuth2TokenResult?> CreateAccessTokenAsync(IHttpEvent ev, UserApplication app, CancellationToken cancellation);
}
-}
+} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/IOauthSessionIdFactory.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/IOauthSessionIdFactory.cs
index 12a7ffe..3fe508f 100644
--- a/libs/VNLib.Plugins.Sessions.OAuth/src/IOauthSessionIdFactory.cs
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/IOauthSessionIdFactory.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.OAuth
@@ -23,11 +23,6 @@
*/
using System;
-using System.Diagnostics.CodeAnalysis;
-
-using VNLib.Net.Http;
-using VNLib.Plugins.Essentials.Oauth.Applications;
-using VNLib.Plugins.Sessions.Cache.Client;
namespace VNLib.Plugins.Sessions.OAuth
{
@@ -37,15 +32,7 @@ namespace VNLib.Plugins.Sessions.OAuth
/// The maxium number of tokens allowed to be created per OAuth application
/// </summary>
int MaxTokensPerApp { get; }
-
- /// <summary>
- /// Allows for custom configuration of the newly created session and
- /// the <see cref="IHttpEvent"/> its attached to
- /// </summary>
- /// <param name="session">The newly created session</param>
- /// <param name="app">The application associated with the session</param>
- /// <param name="entity">The http event that generated the new session</param>
- void InitNewSession(RemoteSession session, UserApplication app, IHttpEvent entity);
+
/// <summary>
/// The time a session is valid for
/// </summary>
@@ -56,19 +43,11 @@ namespace VNLib.Plugins.Sessions.OAuth
/// and required credential information to generate the new session
/// </summary>
/// <returns>The information genreated for the news ession</returns>
- TokenAndSessionIdResult GenerateTokensAndId();
+ GetTokenResult GenerateTokensAndId();
/// <summary>
/// The type of token this session provider generates
/// </summary>
string TokenType { get; }
-
- /// <summary>
- /// Attempts to recover a session id from
- /// </summary>
- /// <param name="entity">The entity to get the session-id for</param>
- /// <param name="sessionId">The found ID for the session if accepted</param>
- /// <returns>True if a session id was found or set for the session</returns>
- bool TryGetSessionId(IHttpEvent entity, [NotNullWhen(true)] out string? sessionId);
}
}
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/O2SessionProviderEntry.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/O2SessionProviderEntry.cs
index 92ea020..0437541 100644
--- a/libs/VNLib.Plugins.Sessions.OAuth/src/O2SessionProviderEntry.cs
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/O2SessionProviderEntry.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.OAuth
@@ -23,34 +23,22 @@
*/
using System;
-using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
-using System.Collections.Generic;
using VNLib.Net.Http;
using VNLib.Utils.Logging;
-using VNLib.Utils.Extensions;
-using VNLib.Data.Caching;
-using VNLib.Plugins.Sessions.Cache.Client;
-using VNLib.Plugins.Essentials;
-using VNLib.Plugins.Essentials.Sessions;
-using VNLib.Plugins.Essentials.Oauth.Tokens;
-using VNLib.Plugins.Essentials.Oauth.Applications;
using VNLib.Plugins.Sessions.OAuth.Endpoints;
-using VNLib.Plugins.Extensions.VNCache;
+using VNLib.Plugins.Essentials.Sessions;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Plugins.Extensions.Loading.Routing;
-using VNLib.Plugins.Extensions.Loading.Sql;
-using VNLib.Plugins.Extensions.Loading.Events;
-
namespace VNLib.Plugins.Sessions.OAuth
{
public sealed class O2SessionProviderEntry : ISessionProvider
{
- const string OAUTH2_CONFIG_KEY = "oauth2";
+ public const string OAUTH2_CONFIG_KEY = "oauth2";
private OAuth2SessionProvider? _sessions;
@@ -63,21 +51,17 @@ namespace VNLib.Plugins.Sessions.OAuth
ValueTask<SessionHandle> ISessionProvider.GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
{
return _sessions!.GetSessionAsync(entity, cancellationToken);
- }
-
+ }
public void Load(PluginBase plugin, ILogProvider localized)
{
- IReadOnlyDictionary<string, JsonElement> oauth2Config = plugin.GetConfigForType<OAuth2SessionProvider>();
+ IConfigScope o2Config = plugin.GetConfig(OAUTH2_CONFIG_KEY);
//Access token endpoint is optional
- if (oauth2Config.TryGetValue("token_path", out JsonElement el))
+ if (o2Config.ContainsKey("token_path"))
{
- //Init auth endpoint
- AccessTokenEndpoint authEp = new(el.GetString()!, plugin, CreateTokenDelegateAsync);
-
- //route auth endpoint
- plugin.Route(authEp);
+ //Create token endpoint
+ plugin.Route<AccessTokenEndpoint>();
}
//Optional revocation endpoint
@@ -87,38 +71,11 @@ namespace VNLib.Plugins.Sessions.OAuth
plugin.Route<RevocationEndpoint>();
}
- int cacheLimit = oauth2Config["cache_size"].GetInt32();
- int maxTokensPerApp = oauth2Config["max_tokens_per_app"].GetInt32();
- int sessionIdSize = (int)oauth2Config["access_token_size"].GetUInt32();
- TimeSpan tokenValidFor = oauth2Config["token_valid_for_sec"].GetTimeSpan(TimeParseType.Seconds);
- TimeSpan cleanupInterval = oauth2Config["gc_interval_sec"].GetTimeSpan(TimeParseType.Seconds);
- string sessionIdPrefix = oauth2Config["cache_prefix"].GetString() ?? throw new KeyNotFoundException($"Missing required key 'cache_prefix' in '{OAUTH2_CONFIG_KEY}' config");
-
- //init the id provider
- OAuth2SessionIdProvider idProv = new(sessionIdPrefix, maxTokensPerApp, sessionIdSize, tokenValidFor);
-
- //Get shared global-cache
- IGlobalCacheProvider globalCache = plugin.GetGlobalCache(localized);
-
- //Create cache store from global cache
- GlobalCacheStore cacheStore = new(globalCache);
-
- //Init session provider now that client is loaded
- _sessions = new(cacheStore, cacheLimit, 100, idProv, plugin.GetContextOptions());
-
- //Schedule cleanup interval with the plugin scheduler
- plugin.ScheduleInterval(_sessions, cleanupInterval);
-
- //Wait and cleanup expired sessions
- _ = plugin.ObserveTask(() => _sessions.CleanupExpiredSessionsAsync(localized, plugin.UnloadToken), 1000);
+ //Init session provider
+ _sessions = plugin.GetOrCreateSingleton<OAuth2SessionProvider>();
+ _sessions.SetLog(localized);
localized.Information("Session provider loaded");
-
- }
-
- private async Task<IOAuth2TokenResult?> CreateTokenDelegateAsync(HttpEntity entity, UserApplication app, CancellationToken cancellation)
- {
- return await _sessions!.CreateAccessTokenAsync(entity, app, cancellation).ConfigureAwait(false);
}
}
} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2Session.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2Session.cs
index 916f55c..605ccbd 100644
--- a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2Session.cs
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2Session.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.OAuth
@@ -23,42 +23,34 @@
*/
using System;
-using System.Threading;
-using System.Threading.Tasks;
+using System.Collections.Generic;
using VNLib.Net.Http;
using VNLib.Plugins.Essentials.Sessions;
+using VNLib.Plugins.Essentials.Extensions;
using VNLib.Plugins.Sessions.Cache.Client;
-using VNLib.Plugins.Sessions.Cache.Client.Exceptions;
-
using static VNLib.Plugins.Essentials.Sessions.ISessionExtensions;
namespace VNLib.Plugins.Sessions.OAuth
{
+
/// <summary>
/// The implementation of the OAuth2 session container for HTTP sessions
/// </summary>
internal sealed class OAuth2Session : RemoteSession
{
- private readonly Action<OAuth2Session> InvalidateCache;
+ public OAuth2Session(string sessionId, IDictionary<string, string> data, bool isNew)
+ : base(sessionId, data, isNew)
+ {}
- /// <summary>
- /// Initalizes a new <see cref="OAuth2Session"/>
- /// </summary>
- /// <param name="sessionId">The session id (or token)</param>
- /// <param name="client">The <see cref="IRemoteCacheStore"/> used as the backing cache provider</param>
- /// <param name="backgroundTimeOut">The ammount of time to wait for a background operation (delete, update, get)</param>
- /// <param name="invalidCache">Called when the session has been marked as invalid and the close even hook is being executed</param>
- public OAuth2Session(string sessionId, IRemoteCacheStore client, TimeSpan backgroundTimeOut, Action<OAuth2Session> invalidCache)
- : base(sessionId, client, backgroundTimeOut)
+ public void InitNewSession(IHttpEvent entity)
{
- InvalidateCache = invalidCache;
- IsInvalid = false;
+ SessionType = SessionType.Web;
+ Created = DateTimeOffset.UtcNow;
+ //Set user-ip address
+ UserIP = entity.Server.GetTrustedIp();
}
- public bool IsInvalid { get; private set; }
-
-
///<inheritdoc/>
///<exception cref="NotSupportedException"></exception>
public override string Token
@@ -79,56 +71,5 @@ namespace VNLib.Plugins.Sessions.OAuth
}
base.IndexerSet(key, value);
}
- ///<inheritdoc/>
- ///<exception cref="SessionStatusException"></exception>
- public override async Task WaitAndLoadAsync(IHttpEvent entity, CancellationToken token = default)
- {
- //Wait to enter lock
- await base.WaitAndLoadAsync(entity, token);
- if (IsInvalid)
- {
- //Release lock
- MainLock.Release();
- throw new SessionStatusException("The session has been invalidated");
- }
- //Set session type
- if (IsNew)
- {
- SessionType = SessionType.OAuth2;
- }
- }
- ///<inheritdoc/>
- protected override async ValueTask<Task?> UpdateResource(bool isAsync, IHttpEvent state)
- {
- Task? result = null;
- //Invalid flag is set, so exit
- if (IsInvalid)
- {
- result = Task.CompletedTask;
- }
- //Check flags in priority level, Invalid is highest state priority
- else if (Flags.IsSet(INVALID_MSK))
- {
- //Clear all stored values
- DataStore!.Clear();
- //Delete the entity syncronously
- await ProcessDeleteAsync();
- //Set invalid flag
- IsInvalid = true;
- //Invlidate cache
- InvalidateCache(this);
- result = Task.CompletedTask;
- }
- else if (Flags.IsSet(MODIFIED_MSK))
- {
- //Send update to server
- result = Task.Run(ProcessUpdateAsync);
- }
-
- //Clear all flags
- Flags.ClearAll();
-
- return result;
- }
}
}
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionConfig.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionConfig.cs
new file mode 100644
index 0000000..5eb9c0c
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionConfig.cs
@@ -0,0 +1,70 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Essentials.Sessions.OAuth
+* File: O2SessionProviderEntry.cs
+*
+* O2SessionProviderEntry.cs is part of VNLib.Plugins.Essentials.Sessions.OAuth which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+using System.Text.Json.Serialization;
+
+using VNLib.Plugins.Extensions.Loading;
+
+
+namespace VNLib.Plugins.Sessions.OAuth
+{
+ sealed class OAuth2SessionConfig : IOnConfigValidation
+ {
+ [JsonPropertyName("max_tokens_per_app")]
+ public int MaxTokensPerApp { get; set; } = 10;
+
+ [JsonPropertyName("access_token_size")]
+ public int AccessTokenSize { get; set; } = 64;
+
+ [JsonPropertyName("token_valid_for_sec")]
+ public int TokenLifeTimeSeconds { get; set; } = 3600;
+
+ [JsonPropertyName("cache_prefix")]
+ public string CachePrefix { get; set; } = "oauth2";
+
+ public void Validate()
+ {
+ if (MaxTokensPerApp < 1)
+ {
+ throw new ArgumentOutOfRangeException("max_tokens_per_app", "You must configure at least 1 Oatuh2 access token per application, or disable this plugin");
+ }
+
+ if (AccessTokenSize < 16)
+ {
+ throw new ArgumentOutOfRangeException("access_token_size", "You must configure an access token size of at least 16 bytes in length");
+ }
+
+ if (TokenLifeTimeSeconds < 1)
+ {
+ throw new ArgumentOutOfRangeException("token_valid_for_sec", "You must configure an access token lifetime");
+ }
+
+ if (string.IsNullOrWhiteSpace(CachePrefix))
+ {
+ throw new ArgumentException("You must specify a cache prefix", "cache_prefix");
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionFactory.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionFactory.cs
new file mode 100644
index 0000000..d811e25
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionFactory.cs
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Essentials.Sessions.OAuth
+* File: OAuth2SessionFactory.cs
+*
+* OAuth2SessionFactory.cs is part of VNLib.Plugins.Essentials.Sessions.OAuth which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System.Collections.Generic;
+
+using VNLib.Net.Http;
+using VNLib.Plugins.Sessions.Cache.Client;
+
+namespace VNLib.Plugins.Sessions.OAuth
+{
+ internal sealed class OAuth2SessionFactory : ISessionFactory<OAuth2Session>
+ {
+ ///<inheritdoc/>
+ public OAuth2Session? GetNewSession(IHttpEvent entity, string sessionId, IDictionary<string, string>? sessionData)
+ {
+ //Initial data should not be null, if so, do not attach session
+ return sessionData == null ? null : new(sessionId, sessionData, false);
+ }
+ }
+} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionIdProvider.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionIdProvider.cs
deleted file mode 100644
index 5e8ad6b..0000000
--- a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionIdProvider.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Essentials.Sessions.OAuth
-* File: OAuth2SessionIdProvider.cs
-*
-* OAuth2SessionIdProvider.cs is part of VNLib.Plugins.Essentials.Sessions.OAuth which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Essentials.Sessions.OAuth is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Essentials.Sessions.OAuth is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-using System.Diagnostics.CodeAnalysis;
-
-using VNLib.Hashing;
-using VNLib.Net.Http;
-using VNLib.Utils.Memory;
-using VNLib.Utils.Extensions;
-using VNLib.Plugins.Essentials.Extensions;
-using VNLib.Plugins.Essentials.Oauth.Applications;
-using VNLib.Plugins.Sessions.Cache.Client;
-using static VNLib.Plugins.Essentials.Oauth.OauthSessionExtensions;
-
-namespace VNLib.Plugins.Sessions.OAuth
-{
- /// <summary>
- /// Generates secure OAuth2 session tokens and initalizes new OAuth2 sessions
- /// </summary>
- internal class OAuth2SessionIdProvider : IOauthSessionIdFactory
- {
- private readonly string SessionIdPrefix;
- private readonly int _bufferSize;
- private readonly int _tokenSize;
-
- ///<inheritdoc/>
- public int MaxTokensPerApp { get; }
- ///<inheritdoc/>
- public TimeSpan SessionValidFor { get; }
- ///<inheritdoc/>
- string IOauthSessionIdFactory.TokenType => "Bearer";
-
- public OAuth2SessionIdProvider(string sessionIdPrefix, int maxTokensPerApp, int tokenSize, TimeSpan validFor)
- {
- SessionIdPrefix = sessionIdPrefix;
- MaxTokensPerApp = maxTokensPerApp;
- SessionValidFor = validFor;
- _tokenSize = tokenSize;
- _bufferSize = tokenSize * 2;
- }
-
- ///<inheritdoc/>
- bool IOauthSessionIdFactory.TryGetSessionId(IHttpEvent entity, [NotNullWhen(true)] out string? sessionId)
- {
- //Get authorization token and make sure its not too large to cause a buffer overflow
- if (entity.Server.HasAuthorization(out string? token) && (token.Length + SessionIdPrefix.Length) <= _bufferSize)
- {
- //Compute session id from token
- sessionId = ComputeSessionIdFromToken(token);
-
- return true;
- }
- else
- {
- sessionId = null;
- }
-
- return false;
- }
-
- private string ComputeSessionIdFromToken(string token)
- {
- //Buffer to copy data to
- using UnsafeMemoryHandle<char> buffer = MemoryUtil.UnsafeAlloc<char>(_bufferSize, true);
-
- //Writer to accumulate data
- ForwardOnlyWriter<char> writer = new(buffer.Span);
-
- //Append session id prefix and token
- writer.Append(SessionIdPrefix);
- writer.Append(token);
-
- //Compute base64 hash of token and
- return ManagedHash.ComputeBase64Hash(writer.AsSpan(), HashAlg.SHA256);
- }
-
- ///<inheritdoc/>
- TokenAndSessionIdResult IOauthSessionIdFactory.GenerateTokensAndId()
- {
- //Alloc buffer for random data
- using UnsafeMemoryHandle<byte> mem = MemoryUtil.UnsafeAlloc<byte>(_tokenSize, true);
-
- //Generate token from random cng bytes
- RandomHash.GetRandomBytes(mem);
-
- //Token is the raw value
- string token = Convert.ToBase64String(mem.Span);
-
- //The session id is the HMAC of the token
- string sessionId = ComputeSessionIdFromToken(token);
-
- //Clear buffer
- MemoryUtil.InitializeBlock(mem.Span);
-
- //Return sessid result
- return new(sessionId, token, null);
- }
-
- ///<inheritdoc/>
- void IOauthSessionIdFactory.InitNewSession(RemoteSession session, UserApplication app, IHttpEvent entity)
- {
- //Store session variables
- session[APP_ID_ENTRY] = app.Id;
- session[TOKEN_TYPE_ENTRY] = "client_credential,bearer";
- session[SCOPES_ENTRY] = app.Permissions;
- session.UserID = app.UserId;
- }
- }
-}
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionProvider.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionProvider.cs
index 7047e6e..1797ddb 100644
--- a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionProvider.cs
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionProvider.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.OAuth
@@ -28,20 +28,18 @@ using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
-using Microsoft.EntityFrameworkCore;
-
using VNLib.Net.Http;
using VNLib.Utils;
using VNLib.Utils.Logging;
using VNLib.Data.Caching.Exceptions;
-using VNLib.Plugins.Sessions.Cache.Client;
using VNLib.Plugins.Essentials;
-using VNLib.Plugins.Essentials.Oauth;
using VNLib.Plugins.Essentials.Sessions;
using VNLib.Plugins.Essentials.Oauth.Tokens;
using VNLib.Plugins.Essentials.Oauth.Applications;
using VNLib.Plugins.Extensions.Loading;
+using VNLib.Plugins.Extensions.Loading.Sql;
using VNLib.Plugins.Extensions.Loading.Events;
+using static VNLib.Plugins.Essentials.Oauth.OauthSessionExtensions;
namespace VNLib.Plugins.Sessions.OAuth
{
@@ -49,139 +47,145 @@ namespace VNLib.Plugins.Sessions.OAuth
/// <summary>
/// Provides OAuth2 session management
/// </summary>
- [ConfigurationName("oauth2")]
- internal sealed class OAuth2SessionProvider : SessionCacheClient, ITokenManager, IIntervalScheduleable
- {
-
- private static readonly SessionHandle NotFoundHandle = new(null, FileProcessArgs.NotFound, null);
-
- private static readonly TimeSpan BackgroundTimeout = TimeSpan.FromSeconds(10);
+ [ConfigurationName(O2SessionProviderEntry.OAUTH2_CONFIG_KEY)]
+ internal sealed class OAuth2SessionProvider : ISessionProvider, ITokenManager, IApplicationTokenFactory
+ {
+ private static readonly SessionHandle Skip = new(null, FileProcessArgs.VirtualSkip, null);
-
- private readonly IOauthSessionIdFactory factory;
+ private readonly OAuth2SessionStore _sessions;
+ private readonly IOauthSessionIdFactory _tokenFactory;
private readonly TokenStore TokenStore;
- private readonly uint MaxConnections;
-
- public OAuth2SessionProvider(IRemoteCacheStore client, int maxCacheItems, uint maxConnections, IOauthSessionIdFactory idFactory, DbContextOptions dbCtx)
- : base(client, maxCacheItems)
+ private readonly string _tokenTypeString;
+ private readonly uint _maxConnections;
+
+ private uint _waitingConnections;
+
+ public bool IsConnected => _sessions.IsConnected;
+
+ public OAuth2SessionProvider(PluginBase plugin, IConfigScope config)
{
- factory = idFactory;
- TokenStore = new(dbCtx);
- MaxConnections = maxConnections;
+ _sessions = plugin.GetOrCreateSingleton<OAuth2SessionStore>();
+ _tokenFactory = plugin.GetOrCreateSingleton<OAuth2TokenFactory>();
+ TokenStore = new(plugin.GetContextOptions());
+ _tokenTypeString = $"client_credential,{_tokenFactory.TokenType}";
}
- ///<inheritdoc/>
- protected override RemoteSession SessionCtor(string sessionId) => new OAuth2Session(sessionId, Store, BackgroundTimeout, InvalidatateCache);
+ public void SetLog(ILogProvider log) => _sessions.SetLog(log);
- private void InvalidatateCache(OAuth2Session session)
+ public ValueTask<SessionHandle> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
{
- lock (CacheLock)
+ //Limit max number of waiting clients and make sure were connected
+ if (!_sessions.IsConnected || _waitingConnections > _maxConnections)
{
- _ = CacheTable.Remove(session.SessionID);
+ //Set 503 for temporary unavail
+ entity.CloseResponse(HttpStatusCode.ServiceUnavailable);
+ return ValueTask.FromResult(Skip);
}
- }
-
- ///<inheritdoc/>
- public async ValueTask<SessionHandle> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
- {
- //Callback to close the session when the handle is closeed
- static ValueTask HandleClosedAsync(ISession session, IHttpEvent entity)
+ ValueTask<OAuth2Session?> result = _sessions.GetSessionAsync(entity, cancellationToken);
+
+ if (result.IsCompleted)
{
- return ((SessionBase)session).UpdateAndRelease(true, entity);
+ OAuth2Session? session = result.GetAwaiter().GetResult();
+
+ //Post process and get handle for session
+ SessionHandle handle = PostProcess(session);
+
+ return ValueTask.FromResult(handle);
}
- try
+ else
{
- //Get session id
- if (!factory.TryGetSessionId(entity, out string? sessionId))
- {
- //Id not allowed/found, so do not attach a session
- return SessionHandle.Empty;
- }
+ return new(AwaitAsyncGet(result));
+ }
+ }
- //Limit max number of waiting clients
- if (!IsConnected || WaitingConnections > MaxConnections)
- {
- //Set 503 for temporary unavail
- entity.CloseResponse(HttpStatusCode.ServiceUnavailable);
- return new SessionHandle(null, FileProcessArgs.VirtualSkip, null);
- }
+ private async Task<SessionHandle> AwaitAsyncGet(ValueTask<OAuth2Session?> async)
+ {
+ //Inct wait count while async waiting
+ _waitingConnections++;
+ try
+ {
+ //await the session
+ OAuth2Session? session = await async.ConfigureAwait(false);
- //Recover the session
- RemoteSession session = await base.GetSessionAsync(entity, sessionId, cancellationToken);
-
- //Session should not be new
- if (session.IsNew)
- {
- //Invalidate the session, so it is deleted
- session.Invalidate();
- await session.UpdateAndRelease(true, entity);
- return SessionHandle.Empty;
- }
- //Make sure session is still valid
- if (session.Created.Add(factory.SessionValidFor) < DateTimeOffset.UtcNow)
- {
- //Invalidate the handle
- session.Invalidate();
- //Flush changes
- await session.UpdateAndRelease(false, entity);
- //Remove the token from the db backing store
- await TokenStore.RevokeTokenAsync(sessionId, cancellationToken);
- //close entity
- entity.CloseResponseError(HttpStatusCode.Unauthorized, ErrorType.InvalidToken, "The token has expired");
- //return a completed handle
- return NotFoundHandle;
- }
-
- return new SessionHandle(session, HandleClosedAsync);
+ //return empty session handle if the session could not be found
+ return PostProcess(session);
}
- //Pass session exceptions
- catch (SessionException)
+ finally
{
- throw;
+ _waitingConnections--;
}
- catch (Exception ex)
+ }
+
+ private SessionHandle PostProcess(OAuth2Session? session)
+ {
+ if (session == null)
{
- throw new SessionException("Exception raised while retreiving or loading OAuth2 session", ex);
+ return SessionHandle.Empty;
+ }
+
+ //Make sure the session has not expired yet
+ if (session.Created.Add(_tokenFactory.SessionValidFor) < DateTimeOffset.UtcNow)
+ {
+ //Invalidate the session, so its technically valid for this request, but will be cleared on this handle close cycle
+ session.Invalidate();
+
+ //Clears important security variables
+ InitNewSession(session, null);
}
+
+ return new SessionHandle(session, OnSessionReleases);
}
+
+ private ValueTask OnSessionReleases(ISession session, IHttpEvent entity) => _sessions.ReleaseSessionAsync((OAuth2Session)session, entity);
+
///<inheritdoc/>
public async Task<IOAuth2TokenResult?> CreateAccessTokenAsync(IHttpEvent ev, UserApplication app, CancellationToken cancellation)
{
//Get a new session for the current connection
- TokenAndSessionIdResult ids = factory.GenerateTokensAndId();
+ GetTokenResult ids = _tokenFactory.GenerateTokensAndId();
+
//try to insert token into the store, may fail if max has been reached
- if (await TokenStore.InsertTokenAsync(ids.SessionId, app.Id!, ids.RefreshToken, factory.MaxTokensPerApp, cancellation) != ERRNO.SUCCESS)
+ if (await TokenStore.InsertTokenAsync(ids.AccessToken, app.Id!, ids.RefreshToken, _tokenFactory.MaxTokensPerApp, cancellation) != ERRNO.SUCCESS)
{
return null;
}
- //Create new session from the session id
- RemoteSession session = SessionCtor(ids.SessionId);
- await session.WaitAndLoadAsync(ev, cancellation);
- try
- {
- //Init new session
- factory.InitNewSession(session, app, ev);
- }
- finally
- {
- await session.UpdateAndRelease(false, ev);
- }
+
+ //Create new session
+ OAuth2Session newSession = _sessions.CreateSession(ev, ids.AccessToken);
+
+ //Init the new session with application information
+ InitNewSession(newSession, app);
+
+ //Commit the new session
+ await _sessions.CommitSessionAsync(newSession);
+
//Init new token result to pass to client
return new OAuth2TokenResult()
{
- ExpiresSeconds = (int)factory.SessionValidFor.TotalSeconds,
- TokenType = factory.TokenType,
+ ExpiresSeconds = (int)_tokenFactory.SessionValidFor.TotalSeconds,
+ TokenType = _tokenFactory.TokenType,
//Return token and refresh token
AccessToken = ids.AccessToken,
RefreshToken = ids.RefreshToken,
};
}
+
+ private void InitNewSession(OAuth2Session session, UserApplication? app)
+ {
+ //Store session variables
+ session[APP_ID_ENTRY] = app?.Id;
+ session[TOKEN_TYPE_ENTRY] = _tokenTypeString;
+ session[SCOPES_ENTRY] = app?.Permissions;
+ session.UserID = app?.UserId;
+ }
+
///<inheritdoc/>
Task ITokenManager.RevokeTokensAsync(IReadOnlyCollection<string> tokens, CancellationToken cancellation)
{
return TokenStore.RevokeTokensAsync(tokens, cancellation);
}
+
///<inheritdoc/>
Task ITokenManager.RevokeTokensForAppAsync(string appId, CancellationToken cancellation)
{
@@ -193,11 +197,11 @@ namespace VNLib.Plugins.Sessions.OAuth
* Interval for removing expired tokens
*/
- ///<inheritdoc/>
- async Task IIntervalScheduleable.OnIntervalAsync(ILogProvider log, CancellationToken cancellationToken)
+ [AsyncInterval(Minutes = 2)]
+ private async Task OnIntervalAsync(ILogProvider log, CancellationToken cancellationToken)
{
//Calculate valid token time
- DateTime validAfter = DateTime.UtcNow.Subtract(factory.SessionValidFor);
+ DateTime validAfter = DateTime.UtcNow.Subtract(_tokenFactory.SessionValidFor);
//Remove tokens from db store
IReadOnlyCollection<ActiveToken> revoked = await TokenStore.CleanupExpiredTokensAsync(validAfter, cancellationToken);
//exception list
@@ -208,17 +212,17 @@ namespace VNLib.Plugins.Sessions.OAuth
try
{
//Remove tokens by thier object id from cache
- await base.Store.DeleteObjectAsync(token.Id, cancellationToken);
+ await _sessions.DeleteTokenAsync(token.Id, cancellationToken);
}
//Ignore if the object has already been removed
catch (ObjectNotFoundException)
{}
catch (Exception ex)
{
- errors = new()
- {
- ex
- };
+#pragma warning disable CA1508 // Avoid dead conditional code
+ errors ??= new();
+#pragma warning restore CA1508 // Avoid dead conditional code
+ errors.Add(ex);
}
}
if (errors?.Count > 0)
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionStore.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionStore.cs
new file mode 100644
index 0000000..8719002
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2SessionStore.cs
@@ -0,0 +1,101 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Essentials.Sessions.OAuth
+* File: OAuth2SessionStore.cs
+*
+* OAuth2SessionStore.cs is part of VNLib.Plugins.Essentials.Sessions.OAuth which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+using VNLib.Hashing;
+using VNLib.Net.Http;
+using VNLib.Utils.Logging;
+using VNLib.Data.Caching;
+using VNLib.Plugins.Sessions.Cache.Client;
+using VNLib.Plugins.Extensions.VNCache;
+using VNLib.Plugins.Extensions.Loading;
+
+
+namespace VNLib.Plugins.Sessions.OAuth
+{
+ [ConfigurationName(O2SessionProviderEntry.OAUTH2_CONFIG_KEY)]
+ internal sealed class OAuth2SessionStore : SessionStore<OAuth2Session>
+ {
+ private ILogProvider _log;
+
+ protected override ISessionIdFactory IdFactory { get; }
+ protected override IRemoteCacheStore Cache { get; }
+ protected override ISessionFactory<OAuth2Session> SessionFactory { get; }
+ protected override ILogProvider Log => _log;
+
+ public bool IsConnected => Cache.IsConnected;
+
+ public OAuth2SessionStore(PluginBase plugin, IConfigScope config)
+ {
+ OAuth2SessionConfig o2Conf = config.DeserialzeAndValidate<OAuth2SessionConfig>();
+
+ //Get global cache
+ IGlobalCacheProvider cache = plugin.GetOrCreateSingleton<VnGlobalCache>()
+ .GetPrefixedCache(o2Conf.CachePrefix, HashAlg.SHA256);
+
+ //Create remote cache
+ Cache = new GlobalCacheStore(cache);
+
+ IdFactory = plugin.GetOrCreateSingleton<OAuth2TokenFactory>();
+
+ SessionFactory = new OAuth2SessionFactory();
+
+ //Default to plugin cache
+ _log = plugin.Log;
+ }
+
+ public void SetLog(ILogProvider log)
+ {
+ _log = log;
+ }
+
+
+ public Task DeleteTokenAsync(string token, CancellationToken cancellation)
+ {
+ return Cache.DeleteObjectAsync(token, cancellation);
+ }
+
+ public OAuth2Session CreateSession(IHttpEvent entity, string sessionId)
+ {
+ //Get the new session
+ OAuth2Session session = SessionFactory.GetNewSession(entity, sessionId, new Dictionary<string, string>(10));
+ //Configure the new session for use
+ session.InitNewSession(entity);
+
+ return session;
+ }
+
+ public async Task CommitSessionAsync(OAuth2Session session)
+ {
+ IDictionary<string, string> sessionData = session.GetSessionData();
+ //Write data to cache
+ await Cache.AddOrUpdateObjectAsync(session.SessionID, null, sessionData);
+ //Good programming, update session
+ session.SessionUpdateComplete();
+ }
+ }
+} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2TokenFactory.cs b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2TokenFactory.cs
new file mode 100644
index 0000000..b452e29
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.OAuth/src/OAuth2TokenFactory.cs
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Essentials.Sessions.OAuth
+* File: OAuth2TokenFactory.cs
+*
+* OAuth2TokenFactory.cs is part of VNLib.Plugins.Essentials.Sessions.OAuth which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Essentials.Sessions.OAuth is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+
+using VNLib.Hashing;
+using VNLib.Net.Http;
+using VNLib.Plugins.Sessions.Cache.Client;
+using VNLib.Plugins.Extensions.Loading;
+using VNLib.Plugins.Essentials.Extensions;
+
+
+namespace VNLib.Plugins.Sessions.OAuth
+{
+ [ConfigurationName(O2SessionProviderEntry.OAUTH2_CONFIG_KEY)]
+ internal sealed class OAuth2TokenFactory : ISessionIdFactory, IOauthSessionIdFactory
+ {
+ private readonly OAuth2SessionConfig _config;
+
+ public OAuth2TokenFactory(PluginBase plugin, IConfigScope config)
+ {
+ //Get the oauth2 config
+ _config = config.DeserialzeAndValidate<OAuth2SessionConfig>();
+ }
+
+ /*
+ * ID Regeneration is always false as OAuth2 sessions
+ * do not allow dynamic ID updates, they require a
+ * negotiation
+ */
+
+ bool ISessionIdFactory.RegenerationSupported => false;
+
+ /*
+ * Connections that do not identify themselves, via a token are
+ * not valid. ID/Tokens must be created at once during
+ * authentication stage.
+ */
+
+ bool ISessionIdFactory.RegenIdOnEmptyEntry => false;
+
+
+ ///<inheritdoc/>
+ int IOauthSessionIdFactory.MaxTokensPerApp => _config.MaxTokensPerApp;
+
+ ///<inheritdoc/>
+ TimeSpan IOauthSessionIdFactory.SessionValidFor => TimeSpan.FromSeconds(_config.TokenLifeTimeSeconds);
+
+ ///<inheritdoc/>
+ string IOauthSessionIdFactory.TokenType => "Bearer";
+
+ ///<inheritdoc/>
+ bool ISessionIdFactory.CanService(IHttpEvent entity)
+ {
+ return entity.Server.HasAuthorization(out _);
+ }
+
+ ///<inheritdoc/>
+ public GetTokenResult GenerateTokensAndId()
+ {
+ //Token is the raw value
+ string token = RandomHash.GetRandomBase64(_config.AccessTokenSize);
+
+ //Return sessid result
+ return new(token, null);
+ }
+
+ string ISessionIdFactory.RegenerateId(IHttpEvent entity)
+ {
+ throw new NotSupportedException("Id regeneration is not supported for OAuth2 sessions");
+ }
+
+ string? ISessionIdFactory.TryGetSessionId(IHttpEvent entity)
+ {
+ return entity.Server.HasAuthorization(out string? token) ? token : null;
+ }
+ }
+} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSession.cs b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSession.cs
index 1457023..7ab4cbe 100644
--- a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSession.cs
+++ b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSession.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.VNCache
@@ -23,91 +23,54 @@
*/
using System;
-using System.Threading;
-using System.Threading.Tasks;
+using System.Collections.Generic;
using VNLib.Net.Http;
using VNLib.Plugins.Essentials.Sessions;
using VNLib.Plugins.Essentials.Extensions;
using VNLib.Plugins.Sessions.Cache.Client;
-using static VNLib.Plugins.Essentials.Sessions.ISessionExtensions;
+
namespace VNLib.Plugins.Sessions.VNCache
{
internal class WebSession : RemoteSession
{
- protected readonly Func<IHttpEvent, string, string> UpdateId;
- private string? _oldId;
+ public WebSession(string sessionId, IDictionary<string, string> sessionData, bool isNew)
+ : base(sessionId, sessionData, isNew)
+ {}
- public WebSession(string sessionId, IRemoteCacheStore client, TimeSpan backgroundTimeOut, Func<IHttpEvent, string, string> UpdateId)
- : base(sessionId, client, backgroundTimeOut)
+ internal void InitNewSession(IHttpEvent entity)
{
- this.UpdateId = UpdateId;
- }
+ SessionType = SessionType.Web;
+ Created = DateTimeOffset.UtcNow;
+ //Set user-ip address
+ UserIP = entity.Server.GetTrustedIp();
- public override async Task WaitAndLoadAsync(IHttpEvent entity, CancellationToken cancellationToken)
- {
- //Wait for the session to load
- await base.WaitAndLoadAsync(entity, cancellationToken);
- //If the session is new, set to web mode
- if (IsNew)
- {
- SessionType = SessionType.Web;
- }
+ /*
+ * We do not need to set the IsModifed flag because the above statments
+ * should set it automatically
+ */
+ //IsModified = true;
}
- private async Task ProcessUpgradeAsync()
+ public override IDictionary<string, string> GetSessionData()
{
- //Setup timeout cancellation for the update, to cancel it
- using CancellationTokenSource cts = new(UpdateTimeout);
- await Client.AddOrUpdateObjectAsync(_oldId!, SessionID, DataStore, cts.Token);
- _oldId = null;
- }
-
- protected override ValueTask<Task?> UpdateResource(bool isAsync, IHttpEvent state)
- {
- Task? result = null;
- //Check flags in priority level, Invalid is highest state priority
+ //Update variables before getting data
if (Flags.IsSet(INVALID_MSK))
{
- //Clear all stored values
- DataStore!.Clear();
- //Reset ip-address
- UserIP = state.Server.GetTrustedIp();
- //Update created time
- Created = DateTimeOffset.UtcNow;
- //Init the new session-data
- this.InitNewSession(state.Server);
- //Restore session type
- SessionType = SessionType.Web;
- //generate new session-id and update the record in the store
- _oldId = SessionID;
- //Update the session-id
- SessionID = UpdateId(state, _oldId);
- //write update to server
- result = Task.Run(ProcessUpgradeAsync);
+ //Sessions that are invalid are destroyed and created later
}
else if (Flags.IsSet(REGEN_ID_MSK))
{
- //generate new session-id and update the record in the store
- _oldId = SessionID;
- //Update the session-id
- SessionID = UpdateId(state, _oldId);
//Update created time
Created = DateTimeOffset.UtcNow;
- //write update to server
- result = Task.Run(ProcessUpgradeAsync);
}
else if (Flags.IsSet(MODIFIED_MSK))
{
- //Send update to server
- result = Task.Run(ProcessUpdateAsync);
+ //Nothing needs to be done here, state will be preserved
}
-
- //Clear all flags
- Flags.ClearAll();
-
- return ValueTask.FromResult<Task?>(null);
+
+ return base.GetSessionData();
}
}
}
diff --git a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionFactory.cs b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionFactory.cs
new file mode 100644
index 0000000..db77521
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionFactory.cs
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Essentials.Sessions.VNCache
+* File: WebSessionFactory.cs
+*
+* WebSessionFactory.cs is part of VNLib.Plugins.Essentials.Sessions.VNCache which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Essentials.Sessions.VNCache is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Essentials.Sessions.VNCache is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+using System.Collections.Generic;
+
+using VNLib.Net.Http;
+using VNLib.Plugins.Sessions.Cache.Client;
+
+
+namespace VNLib.Plugins.Sessions.VNCache
+{
+ internal sealed class WebSessionFactory : ISessionFactory<WebSession>
+ {
+ private static IDictionary<string, string> GetDict() => new Dictionary<string, string>(10, StringComparer.OrdinalIgnoreCase);
+
+ public WebSession GetNewSession(IHttpEvent connection, string sessionId, IDictionary<string, string>? sessionData)
+ {
+ /*
+ * Create the new session and initialize it
+ * If the initial data does not exist, create a new default dictionary
+ * the session is considered new if the session data was empty
+ */
+ WebSession ws = new(sessionId, sessionData ?? GetDict(), sessionData == null);
+
+ if (ws.IsNew)
+ {
+ //init fresh session
+ ws.InitNewSession(connection);
+ }
+
+ return ws;
+ }
+ }
+}
diff --git a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionIdFactory.cs b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionIdFactory.cs
new file mode 100644
index 0000000..96e9938
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionIdFactory.cs
@@ -0,0 +1,100 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Essentials.Sessions.VNCache
+* File: WebSessionIdFactory.cs
+*
+* WebSessionIdFactory.cs is part of VNLib.Plugins.Essentials.Sessions.VNCache which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Essentials.Sessions.VNCache is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Essentials.Sessions.VNCache is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+using System.Collections.Generic;
+
+using VNLib.Hashing;
+using VNLib.Net.Http;
+using VNLib.Utils.Extensions;
+using VNLib.Plugins.Essentials.Extensions;
+using VNLib.Plugins.Extensions.Loading;
+using VNLib.Plugins.Sessions.Cache.Client;
+
+namespace VNLib.Plugins.Sessions.VNCache
+{
+ /// <summary>
+ /// <see cref="IWebSessionIdFactory"/> implementation, using
+ /// http cookies as session id storage
+ /// </summary>
+ [ConfigurationName(WebSessionProviderEntry.WEB_SESSION_CONFIG)]
+ internal sealed class WebSessionIdFactory : ISessionIdFactory
+ {
+ public TimeSpan ValidFor { get; }
+
+ ///<inheritdoc/>
+ public bool RegenerationSupported { get; } = true;
+ ///<inheritdoc/>
+ public bool RegenIdOnEmptyEntry { get; } = true;
+
+
+ private readonly string SessionCookieName;
+ private readonly int _cookieSize;
+
+ /// <summary>
+ /// Initialzies a new web session Id factory
+ /// </summary>
+ /// <param name="cookieSize">The size of the cookie in bytes</param>
+ /// <param name="sessionCookieName">The name of the session cookie</param>
+ /// <param name="validFor">The time the session cookie is valid for</param>
+ public WebSessionIdFactory(uint cookieSize, string sessionCookieName, TimeSpan validFor)
+ {
+ ValidFor = validFor;
+ SessionCookieName = sessionCookieName;
+ _cookieSize = (int)cookieSize;
+ }
+
+ public WebSessionIdFactory(PluginBase pbase, IConfigScope config)
+ {
+ _cookieSize = (int)config["cookie_size"].GetUInt32();
+ SessionCookieName = config["cookie_name"].GetString()
+ ?? throw new KeyNotFoundException($"Missing required element 'cookie_name' for config '{WebSessionProviderEntry.WEB_SESSION_CONFIG}'");
+ ValidFor = config["valid_for_sec"].GetTimeSpan(TimeParseType.Seconds);
+ }
+
+
+ public string RegenerateId(IHttpEvent entity)
+ {
+ //Random hex hash
+ string cookie = RandomHash.GetRandomBase32(_cookieSize);
+
+ //Set the session id cookie
+ entity.Server.SetCookie(SessionCookieName, cookie, ValidFor, secure: true, httpOnly: true);
+
+ //return session-id value from cookie value
+ return cookie;
+ }
+
+ public string? TryGetSessionId(IHttpEvent entity)
+ {
+ //Get session cookie
+ return entity.Server.RequestCookies.GetValueOrDefault(SessionCookieName);
+ }
+
+ public bool CanService(IHttpEvent entity)
+ {
+ return entity.Server.RequestCookies.ContainsKey(SessionCookieName) || entity.Server.IsBrowser();
+ }
+ }
+} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionIdFactoryImpl.cs b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionIdFactoryImpl.cs
deleted file mode 100644
index 004d019..0000000
--- a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionIdFactoryImpl.cs
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
-* Copyright (c) 2022 Vaughn Nugent
-*
-* Library: VNLib
-* Package: VNLib.Plugins.Essentials.Sessions.VNCache
-* File: WebSessionIdFactoryImpl.cs
-*
-* WebSessionIdFactoryImpl.cs is part of VNLib.Plugins.Essentials.Sessions.VNCache which is part of the larger
-* VNLib collection of libraries and utilities.
-*
-* VNLib.Plugins.Essentials.Sessions.VNCache is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* VNLib.Plugins.Essentials.Sessions.VNCache is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program. If not, see https://www.gnu.org/licenses/.
-*/
-
-using System;
-using System.Diagnostics.CodeAnalysis;
-
-using VNLib.Hashing;
-using VNLib.Net.Http;
-using VNLib.Utils.Memory;
-using VNLib.Utils.Extensions;
-using VNLib.Plugins.Essentials.Extensions;
-
-namespace VNLib.Plugins.Sessions.VNCache
-{
- /// <summary>
- /// <see cref="IWebSessionIdFactory"/> implementation, using
- /// http cookies as session id storage
- /// </summary>
- internal sealed class WebSessionIdFactoryImpl : IWebSessionIdFactory
- {
- public TimeSpan ValidFor { get; }
-
- public string GenerateSessionId(IHttpEvent entity)
- {
- //Random hex hash
- string cookie = RandomHash.GetRandomBase32(_tokenSize);
-
- //Set the session id cookie
- entity.Server.SetCookie(SessionCookieName, cookie, ValidFor, secure: true, httpOnly: true);
-
- //return session-id value from cookie value
- return ComputeSessionIdFromCookie(cookie);
- }
-
- public bool TryGetSessionId(IHttpEvent entity, [NotNullWhen(true)] out string? sessionId)
- {
- //Get authorization token and make sure its not too large to cause a buffer overflow
- if (entity.Server.GetCookie(SessionCookieName, out string? cookie) && (cookie.Length + SessionIdPrefix.Length) <= _bufferSize)
- {
- //Compute session id from token
- sessionId = ComputeSessionIdFromCookie(cookie);
-
- return true;
- }
- //Only add sessions for user-agents
- else if(entity.Server.IsBrowser())
- {
- //Get a new session id
- sessionId = GenerateSessionId(entity);
-
- return true;
- }
- else
- {
- sessionId = null;
- return false;
- }
- }
-
- private readonly string SessionCookieName;
- private readonly string SessionIdPrefix;
- private readonly int _bufferSize;
- private readonly int _tokenSize;
-
- /// <summary>
- /// Initialzies a new web session Id factory
- /// </summary>
- /// <param name="cookieSize">The size of the cookie in bytes</param>
- /// <param name="sessionCookieName">The name of the session cookie</param>
- /// <param name="sessionIdPrefix">The session-id internal prefix</param>
- /// <param name="validFor">The time the session cookie is valid for</param>
- public WebSessionIdFactoryImpl(uint cookieSize, string sessionCookieName, string sessionIdPrefix, TimeSpan validFor)
- {
- ValidFor = validFor;
- SessionCookieName = sessionCookieName;
- SessionIdPrefix = sessionIdPrefix;
- _tokenSize = (int)cookieSize;
- //Calc buffer size
- _bufferSize = Math.Max(32, ((int)cookieSize * 3) + sessionIdPrefix.Length);
- }
-
-
- private string ComputeSessionIdFromCookie(string sessionId)
- {
- //Buffer to copy data to
- using UnsafeMemoryHandle<char> buffer = MemoryUtil.UnsafeAlloc<char>(_bufferSize, true);
-
- //Writer to accumulate data
- ForwardOnlyWriter<char> writer = new(buffer.Span);
-
- //Append prefix and session id
- writer.Append(SessionIdPrefix);
- writer.Append(sessionId);
-
- //Compute base64 hash of token and
- return ManagedHash.ComputeBase64Hash(writer.AsSpan(), HashAlg.SHA256);
- }
- }
-} \ No newline at end of file
diff --git a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProvider.cs b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProvider.cs
index 0fd981b..d2b1e7e 100644
--- a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProvider.cs
+++ b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProvider.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.VNCache
@@ -25,117 +25,105 @@
using System;
using System.Threading;
using System.Threading.Tasks;
-using System.Collections.Generic;
using VNLib.Net.Http;
+using VNLib.Utils.Extensions;
using VNLib.Plugins.Essentials;
using VNLib.Plugins.Essentials.Sessions;
using VNLib.Plugins.Extensions.Loading;
-using VNLib.Plugins.Sessions.Cache.Client;
namespace VNLib.Plugins.Sessions.VNCache
{
- /// <summary>
- /// The implementation of a VNCache web based session
- /// </summary>
- [ConfigurationName("web")]
- internal sealed class WebSessionProvider : SessionCacheClient, ISessionProvider
+
+ [ConfigurationName(WebSessionProviderEntry.WEB_SESSION_CONFIG)]
+ internal sealed class WebSessionProvider : ISessionProvider
{
- static readonly TimeSpan BackgroundUpdateTimeout = TimeSpan.FromSeconds(10);
-
- private readonly IWebSessionIdFactory factory;
- private readonly uint MaxConnections;
-
- /// <summary>
- /// Initializes a new <see cref="WebSessionProvider"/>
- /// </summary>
- /// <param name="client">The cache client to make cache operations against</param>
- /// <param name="maxCacheItems">The max number of items to store in cache</param>
- /// <param name="maxWaiting">The maxium number of waiting session events before 503s are sent</param>
- /// <param name="factory">The session-id factory</param>
- public WebSessionProvider(IRemoteCacheStore client, int maxCacheItems, uint maxWaiting, IWebSessionIdFactory factory) : base(client, maxCacheItems)
+ private static readonly SessionHandle _vf = new (null, FileProcessArgs.VirtualSkip, null);
+
+ private readonly TimeSpan _validFor;
+ private readonly WebSessionStore _sessions;
+ private readonly uint _maxConnections;
+
+ private uint _waitingConnections;
+
+ public bool IsConnected => _sessions.IsConnected;
+
+ public WebSessionProvider(PluginBase plugin, IConfigScope config)
{
- this.factory = factory;
- MaxConnections = maxWaiting;
+ _validFor = config["valid_for_sec"].GetTimeSpan(TimeParseType.Seconds);
+ _maxConnections = config["max_waiting_connections"].GetUInt32();
+
+ //Init session provider
+ _sessions = plugin.GetOrCreateSingleton<WebSessionStore>();
}
- private string UpdateSessionId(IHttpEvent entity, string oldId)
+ private SessionHandle PostProcess(WebSession? session)
{
- //Generate and set a new sessionid
- string newid = factory.GenerateSessionId(entity);
- //Aquire lock on cache
- lock (CacheLock)
+ if (session == null)
{
- //Change the cache lookup id
- if (CacheTable.Remove(oldId, out RemoteSession? session))
- {
- CacheTable.Add(newid, session);
- }
+ return SessionHandle.Empty;
}
- return newid;
+
+ //Make sure the session has not expired yet
+ if (session.Created.Add(_validFor) < DateTimeOffset.UtcNow)
+ {
+ //Invalidate the session, so its technically valid for this request, but will be cleared on this handle close cycle
+ session.Invalidate();
+
+ //Clear basic login status
+ session.Token = null;
+ session.UserID = null;
+ session.Privilages = 0;
+ session.SetLoginToken(null);
+ }
+
+ return new SessionHandle(session, OnSessionReleases);
}
-
- protected override RemoteSession SessionCtor(string sessionId) => new WebSession(sessionId, Store, BackgroundUpdateTimeout, UpdateSessionId);
- public async ValueTask<SessionHandle> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
+ private ValueTask OnSessionReleases(ISession session, IHttpEvent entity) => _sessions.ReleaseSessionAsync((WebSession)session, entity);
+
+ public ValueTask<SessionHandle> GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
{
- //Callback to close the session when the handle is closeed
- static ValueTask HandleClosedAsync(ISession session, IHttpEvent entity)
+ //Limit max number of waiting clients and make sure were connected
+ if (!_sessions.IsConnected || _waitingConnections > _maxConnections)
{
- return (session as SessionBase)!.UpdateAndRelease(true, entity);
+ //Set 503 for temporary unavail
+ entity.CloseResponse(System.Net.HttpStatusCode.ServiceUnavailable);
+ return ValueTask.FromResult(_vf);
}
-
- try
+
+ ValueTask<WebSession?> result = _sessions.GetSessionAsync(entity, cancellationToken);
+
+ if (result.IsCompleted)
{
- //Get session id
- if (!factory.TryGetSessionId(entity, out string? sessionId))
- {
- //Id not allowed/found, so do not attach a session
- return SessionHandle.Empty;
- }
-
- //Limit max number of waiting clients and make sure were connected
- if (!IsConnected || WaitingConnections > MaxConnections)
- {
- //Set 503 for temporary unavail
- entity.CloseResponse(System.Net.HttpStatusCode.ServiceUnavailable);
- return new SessionHandle(null, FileProcessArgs.VirtualSkip, null);
- }
-
- //Get session
- RemoteSession session = await GetSessionAsync(entity, sessionId, cancellationToken);
-
- //If the session is new (not in cache), then overwrite the session id with a new one as user may have specified their own
- if (session.IsNew)
- {
- session.RegenID();
- }
-
- //Make sure the session has not expired yet
- if (session.Created.Add(factory.ValidFor) < DateTimeOffset.UtcNow)
- {
- //Invalidate the session, so its technically valid for this request, but will be cleared on this handle close cycle
- session.Invalidate();
- //Clear basic login status
- session.Token = null;
- session.UserID = null;
- session.Privilages = 0;
- session.SetLoginToken(null);
- }
-
- return new SessionHandle(session, HandleClosedAsync);
+ WebSession? session = result.GetAwaiter().GetResult();
+
+ //Post process and get handle for session
+ SessionHandle handle = PostProcess(session);
+
+ return ValueTask.FromResult(handle);
}
- catch (OperationCanceledException)
+ else
{
- throw;
+ return new(AwaitAsyncGet(result));
}
- catch (SessionException)
+ }
+
+ private async Task<SessionHandle> AwaitAsyncGet(ValueTask<WebSession?> async)
+ {
+ //Inct wait count while async waiting
+ _waitingConnections++;
+ try
{
- throw;
+ //await the session
+ WebSession? session = await async.ConfigureAwait(false);
+
+ //return empty session handle if the session could not be found
+ return PostProcess(session);
}
- catch (Exception ex)
+ finally
{
- throw new SessionException("Exception raised while retreiving or loading Web session", ex);
+ _waitingConnections--;
}
}
}
diff --git a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProviderEntry.cs b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProviderEntry.cs
index f0a7caa..3b1b1ac 100644
--- a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProviderEntry.cs
+++ b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionProviderEntry.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Sessions.VNCache
@@ -23,27 +23,23 @@
*/
using System;
-using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
-using System.Collections.Generic;
using VNLib.Net.Http;
using VNLib.Utils.Logging;
-using VNLib.Utils.Extensions;
-using VNLib.Data.Caching;
-using VNLib.Plugins.Sessions.Cache.Client;
using VNLib.Plugins.Extensions.Loading;
-using VNLib.Plugins.Extensions.VNCache;
using VNLib.Plugins.Essentials.Sessions;
namespace VNLib.Plugins.Sessions.VNCache
{
+
public sealed class WebSessionProviderEntry : ISessionProvider
{
- const string WEB_SESSION_CONFIG = "web";
+ internal const string WEB_SESSION_CONFIG = "web";
private WebSessionProvider? _sessions;
+
//Web sessions can always be provided so long as cache is loaded
public bool CanProcess(IHttpEvent entity) => _sessions != null && _sessions.IsConnected;
@@ -53,32 +49,11 @@ namespace VNLib.Plugins.Sessions.VNCache
return _sessions!.GetSessionAsync(entity, cancellationToken);
}
+
public void Load(PluginBase plugin, ILogProvider localized)
{
- //Try get vncache config element
- IReadOnlyDictionary<string, JsonElement> webSessionConfig = plugin.GetConfigForType<WebSessionProvider>();
-
- uint cookieSize = webSessionConfig["cookie_size"].GetUInt32();
- string cookieName = webSessionConfig["cookie_name"].GetString() ?? throw new KeyNotFoundException($"Missing required element 'cookie_name' for config '{WEB_SESSION_CONFIG}'");
- string cachePrefix = webSessionConfig["cache_prefix"].GetString() ?? throw new KeyNotFoundException($"Missing required element 'cache_prefix' for config '{WEB_SESSION_CONFIG}'");
- int cacheLimit = (int)webSessionConfig["cache_size"].GetUInt32();
- uint maxConnections = webSessionConfig["max_waiting_connections"].GetUInt32();
- TimeSpan validFor = webSessionConfig["valid_for_sec"].GetTimeSpan(TimeParseType.Seconds);
-
- //Init id factory
- WebSessionIdFactoryImpl idFactory = new(cookieSize, cookieName, cachePrefix, validFor);
-
- //Get shared global-cache
- IGlobalCacheProvider globalCache = plugin.GetGlobalCache(localized);
-
- //Create cache store from global cache
- GlobalCacheStore cacheStore = new(globalCache);
-
- //Init provider
- _sessions = new(cacheStore, cacheLimit, maxConnections, idFactory);
-
- //Load and run cached sessions on deferred task lib
- _ = plugin.ObserveTask(() => _sessions.CleanupExpiredSessionsAsync(localized, plugin.UnloadToken), 1000);
+ //Load session provider
+ _sessions = plugin.GetOrCreateSingleton<WebSessionProvider>();
localized.Information("Session provider loaded");
}
diff --git a/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionStore.cs b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionStore.cs
new file mode 100644
index 0000000..6560f57
--- /dev/null
+++ b/libs/VNLib.Plugins.Sessions.VNCache/src/WebSessionStore.cs
@@ -0,0 +1,150 @@
+/*
+* Copyright (c) 2023 Vaughn Nugent
+*
+* Library: VNLib
+* Package: VNLib.Plugins.Essentials.Sessions.VNCache
+* File: WebSessionStore.cs
+*
+* WebSessionStore.cs is part of VNLib.Plugins.Essentials.Sessions.VNCache which is part of the larger
+* VNLib collection of libraries and utilities.
+*
+* VNLib.Plugins.Essentials.Sessions.VNCache is free software: you can redistribute it and/or modify
+* it under the terms of the GNU Affero General Public License as
+* published by the Free Software Foundation, either version 3 of the
+* License, or (at your option) any later version.
+*
+* VNLib.Plugins.Essentials.Sessions.VNCache is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU Affero General Public License for more details.
+*
+* You should have received a copy of the GNU Affero General Public License
+* along with this program. If not, see https://www.gnu.org/licenses/.
+*/
+
+using System;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+using VNLib.Net.Http;
+using VNLib.Hashing;
+using VNLib.Utils.Logging;
+using VNLib.Data.Caching;
+using VNLib.Plugins.Extensions.Loading;
+using VNLib.Plugins.Sessions.Cache.Client;
+using VNLib.Plugins.Extensions.VNCache;
+using VNLib.Plugins.Essentials.Sessions;
+
+namespace VNLib.Plugins.Sessions.VNCache
+{
+ [ConfigurationName(WebSessionProviderEntry.WEB_SESSION_CONFIG)]
+ internal sealed class WebSessionStore : SessionStore<WebSession>
+ {
+ private ILogProvider? baseLog;
+
+ protected override ISessionIdFactory IdFactory { get; }
+ protected override IRemoteCacheStore Cache { get; }
+ protected override ISessionFactory<WebSession> SessionFactory { get; }
+ protected override ILogProvider Log => baseLog!;
+
+ public WebSessionStore(PluginBase pbase, IConfigScope config)
+ {
+ //Get id factory
+ IdFactory = pbase.GetOrCreateSingleton<WebSessionIdFactory>();
+
+ //Session factory
+ SessionFactory = new WebSessionFactory();
+
+ /*
+ * Init prefixed cache, a prefix key is required from
+ * the config
+ */
+
+ string cachePrefix = config["cache_prefix"].GetString()
+ ?? throw new KeyNotFoundException($"Missing required element 'cache_prefix' for config '{WebSessionProviderEntry.WEB_SESSION_CONFIG}'");
+
+ //Create a simple prefix cache provider
+ IGlobalCacheProvider cache = pbase.GetOrCreateSingleton<VnGlobalCache>()
+ .GetPrefixedCache(cachePrefix, HashAlg.SHA256);
+
+ //Create cache store from global cache
+ Cache = new GlobalCacheStore(cache);
+
+ //Default log to plugin log
+ baseLog = pbase.Log;
+ }
+
+ public void InitLog(ILogProvider log)
+ {
+ baseLog = log;
+ }
+
+ /// <summary>
+ /// A value that indicates if the remote cache client is connected
+ /// </summary>
+ public bool IsConnected => Cache.IsConnected;
+
+ public override ValueTask ReleaseSessionAsync(WebSession session, IHttpEvent entity)
+ {
+ //Get status flags first
+ SessionStatus status = session.GetStatus();
+
+ //If status is delete, we need to invalidate the session, and copy its security information
+ if(status.HasFlag(SessionStatus.Delete))
+ {
+ //Run delete/cleanup
+ Task delete = DeleteSessionAsync(session);
+
+ //Regenid and create new session
+ string newId = IdFactory.RegenerateId(entity);
+
+ //Get new session empty session for the connection
+ WebSession newSession = SessionFactory.GetNewSession(entity, newId, null);
+
+ //Reset security information for new session
+ newSession.InitNewSession(entity.Server);
+
+ IDictionary<string, string> data = newSession.GetSessionData();
+
+ //commit session to cache
+ Task add = Cache.AddOrUpdateObjectAsync(newId, null, data);
+
+ /*
+ * Call complete on session for good practice, this SHOULD be
+ * called after the update has been awaited though.
+ *
+ * We also do not need to use the mutal exclusion mechanism because
+ * no other connections should have this session's id yet.
+ */
+ newSession.SessionUpdateComplete();
+
+ //Await the invalidation async
+ return new(AwaitInvalidate(delete, add));
+ }
+ else
+ {
+ return base.ReleaseSessionAsync(session, entity);
+ }
+ }
+
+ private static async Task AwaitInvalidate(Task delete, Task addNew)
+ {
+ try
+ {
+ await Task.WhenAll(delete, addNew);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (SessionException)
+ {
+ throw;
+ }
+ catch(Exception ex)
+ {
+ throw new SessionException("An exception occured during session invalidation", ex);
+ }
+ }
+ }
+}
diff --git a/plugins/SessionProvider/src/RuntimeSessionProvider.cs b/plugins/SessionProvider/src/RuntimeSessionProvider.cs
index 95295de..28397c9 100644
--- a/plugins/SessionProvider/src/RuntimeSessionProvider.cs
+++ b/plugins/SessionProvider/src/RuntimeSessionProvider.cs
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: SessionProvider
@@ -33,7 +33,7 @@ using VNLib.Plugins.Extensions.Loading;
namespace VNLib.Plugins.Essentials.Sessions
{
- sealed class RuntimeSessionProvider : VnDisposeable, ISessionProvider
+ internal sealed class RuntimeSessionProvider : VnDisposeable, ISessionProvider
{
private readonly AssemblyLoader<ISessionProvider> _asm;
diff --git a/plugins/SessionProvider/src/SessionClientEntryPoint.cs b/plugins/SessionProvider/src/SessionProviderEntry.cs
index ae3d166..b3f924f 100644
--- a/plugins/SessionProvider/src/SessionClientEntryPoint.cs
+++ b/plugins/SessionProvider/src/SessionProviderEntry.cs
@@ -1,11 +1,11 @@
/*
-* Copyright (c) 2022 Vaughn Nugent
+* Copyright (c) 2023 Vaughn Nugent
*
* Library: VNLib
* Package: SessionProvider
-* File: SessionClientEntryPoint.cs
+* File: SessionProviderEntry.cs
*
-* SessionClientEntryPoint.cs is part of SessionProvider which is part of the larger
+* SessionProviderEntry.cs is part of SessionProvider which is part of the larger
* VNLib collection of libraries and utilities.
*
* SessionProvider is free software: you can redistribute it and/or modify
@@ -28,10 +28,13 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
+using System.ComponentModel.Design;
+using VNLib.Net.Http;
+using VNLib.Utils;
using VNLib.Utils.Logging;
using VNLib.Utils.Extensions;
-using VNLib.Net.Http;
+using VNLib.Plugins.Attributes;
using VNLib.Plugins.Extensions.Loading;
namespace VNLib.Plugins.Essentials.Sessions
@@ -39,30 +42,25 @@ namespace VNLib.Plugins.Essentials.Sessions
/// <summary>
/// The implementation type for dynamic loading of unified session providers
/// </summary>
- public sealed class SessionClientEntryPoint : PluginBase, ISessionProvider
+ public sealed class SessionProviderEntry : PluginBase
{
///<inheritdoc/>
public override string PluginName => "Essentials.Sessions";
- private RuntimeSessionProvider[] ProviderArray = Array.Empty<RuntimeSessionProvider>();
-
+ private SessionProvider? _provider;
- ValueTask<SessionHandle> ISessionProvider.GetSessionAsync(IHttpEvent entity, CancellationToken token)
- {
- //Loop through providers
- for (int i = 0; i < ProviderArray.Length; i++)
- {
- //Check if provider can process the entity
- if (ProviderArray[i].CanProcess(entity))
- {
- //Get session
- return ProviderArray[i].GetSessionAsync(entity, token);
- }
- }
+ /*
+ * Declare a service configuration method to
+ * expose the session provider
+ */
- //Return empty session
- return new ValueTask<SessionHandle>(SessionHandle.Empty);
+ [ServiceConfigurator]
+ public void ConfigureServices(IServiceContainer services)
+ {
+ //publish the service
+ services.AddService(typeof(ISessionProvider), _provider);
}
+
protected override void OnLoad()
{
@@ -110,9 +108,9 @@ namespace VNLib.Plugins.Essentials.Sessions
if(providers.Count > 0)
{
//Create array for searching for providers
- ProviderArray = providers.ToArray();
+ _provider = new(providers.ToArray());
- Log.Information("Loaded {count} session providers", ProviderArray.Length);
+ Log.Information("Loaded {count} session providers", providers.Count);
}
else
{
@@ -121,13 +119,6 @@ namespace VNLib.Plugins.Essentials.Sessions
Log.Information("Plugin loaded");
}
- catch (KeyNotFoundException knf)
- {
- //Dispose providers
- providers.ForEach(static s => s.Dispose());
-
- Log.Warn("Plugin configuration was missing required variables {var}", knf.Message);
- }
catch
{
//Dispose providers
@@ -138,12 +129,6 @@ namespace VNLib.Plugins.Essentials.Sessions
protected override void OnUnLoad()
{
- //Cleanup assemblies
- ProviderArray.TryForeach(static p => p.Dispose());
-
- //Clear array
- ProviderArray = Array.Empty<RuntimeSessionProvider>();
-
Log.Information("Plugin unloaded");
}
@@ -154,5 +139,46 @@ namespace VNLib.Plugins.Essentials.Sessions
return;
}
}
+
+ /*
+ * When exposing the session provider as a service, it may be disposed by the
+ * service container if its delcared as disposable.
+ */
+
+ private sealed class SessionProvider : VnDisposeable, ISessionProvider, IDisposable
+ {
+ private RuntimeSessionProvider[] ProviderArray = Array.Empty<RuntimeSessionProvider>();
+
+ public SessionProvider(RuntimeSessionProvider[] loaded)
+ {
+ ProviderArray = loaded;
+ }
+
+ ValueTask<SessionHandle> ISessionProvider.GetSessionAsync(IHttpEvent entity, CancellationToken cancellationToken)
+ {
+ //Loop through providers
+ for (int i = 0; i < ProviderArray.Length; i++)
+ {
+ //Check if provider can process the entity
+ if (ProviderArray[i].CanProcess(entity))
+ {
+ //Get session
+ return ProviderArray[i].GetSessionAsync(entity, cancellationToken);
+ }
+ }
+
+ //Return empty session
+ return new ValueTask<SessionHandle>(SessionHandle.Empty);
+ }
+
+ protected override void Free()
+ {
+ //Remove current providers so we can dispose them
+ RuntimeSessionProvider[] current = Interlocked.Exchange(ref ProviderArray, Array.Empty<RuntimeSessionProvider>());
+
+ //Cleanup assemblies
+ current.TryForeach(static p => p.Dispose());
+ }
+ }
}
}