aboutsummaryrefslogtreecommitdiff
path: root/Libs/VNLib.Plugins.Sessions.Cache.Client/SessionCacheClient.cs
blob: de0e370a1763bc7d7b3a709abf577975b33ff871 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

using VNLib.Utils;
using VNLib.Utils.Memory.Caching;
using VNLib.Net.Http;
using VNLib.Net.Messaging.FBM.Client;
using VNLib.Plugins.Essentials.Sessions;

#nullable enable

namespace VNLib.Plugins.Sessions.Cache.Client
{
 
    /// <summary>
    /// A client that allows access to sessions located on external servers
    /// </summary>
    public abstract class SessionCacheClient : VnDisposeable, ICacheHolder
    {
        public class LRUSessionStore<T> : LRUCache<string, T> where T : ISession, ICacheable
        {
            public override bool IsReadOnly => false;
            protected override int MaxCapacity { get; }

            public LRUSessionStore(int maxCapacity) : base(StringComparer.Ordinal) => MaxCapacity = maxCapacity;

            protected override bool CacheMiss(string key, [NotNullWhen(true)] out T? value)
            {
                value = default;
                return false;
            }
            protected override void Evicted(KeyValuePair<string, T> evicted)
            {
                //Evice record
                evicted.Value.Evicted();
            }
        }

        protected readonly LRUSessionStore<RemoteSession> CacheTable;
        protected readonly object CacheLock;
        protected readonly int MaxLoadedEntires;

        protected FBMClient Client { get; }

        /// <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>
        public SessionCacheClient(FBMClient client, int maxCacheItems)
        {
            MaxLoadedEntires = maxCacheItems;
            CacheLock = new();
            CacheTable = new(maxCacheItems);
            Client = client;
            //Listen for close events
            Client.ConnectionClosed += Client_ConnectionClosed;
        }

        private void Client_ConnectionClosed(object? sender, EventArgs e) => CacheHardClear();

        /// <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)
        {
            Check();
            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
                }
                try
                {
                    //Load session-data
                    await session.WaitAndLoadAsync(entity, cancellationToken);
                    return session;
                }
                catch
                {
                    //Remove the invalid cached session
                    lock (CacheLock)
                    {
                        _ = CacheTable.Remove(sessionId);
                    }
                    throw;
                }
            }
            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);

        ///<inheritdoc/>
        public void CacheClear()
        {

        }
        ///<inheritdoc/>
        public void CacheHardClear()
        {
            //Cleanup cache when disconnected
            lock (CacheLock)
            {
                CacheTable.Clear();
                foreach (RemoteSession session in (IEnumerable<RemoteSession>)CacheTable)
                {
                    session.Evicted();
                }
                CacheTable.Clear();
            }
        }

        protected override void Free()
        {
            //Unsub from events
            Client.ConnectionClosed -= Client_ConnectionClosed;
            //Clear all cached sessions
            CacheHardClear();
        }
    }
}