diff options
Diffstat (limited to 'libs/VNLib.Plugins.Sessions.VNCache/src')
7 files changed, 408 insertions, 296 deletions
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); + } + } + } +} |