aboutsummaryrefslogtreecommitdiff
path: root/Libs/VNLib.Plugins.Essentials.Sessions/MemorySession.cs
blob: d365cd2a8896dba06239448919aee7a210a94067 (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
/*
* 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 static VNLib.Plugins.Essentials.Sessions.ISessionExtensions;

#nullable enable

namespace VNLib.Plugins.Essentials.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 tokens/login hashes, we can set the upgrade flag
                case TOKEN_ENTRY:
                case LOGIN_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);
      
    }
}