aboutsummaryrefslogtreecommitdiff
path: root/plugins/SessionProvider/src/SessionProviderEntry.cs
blob: b3f924f16a9d325c66fd54465792a1fb17dcf6f9 (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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: SessionProvider
* File: SessionProviderEntry.cs 
*
* 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 
* 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.
*
* SessionProvider 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.IO;
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.Plugins.Attributes;
using VNLib.Plugins.Extensions.Loading;

namespace VNLib.Plugins.Essentials.Sessions
{
    /// <summary>
    /// The implementation type for dynamic loading of unified session providers 
    /// </summary>
    public sealed class SessionProviderEntry : PluginBase
    {       
        ///<inheritdoc/>
        public override string PluginName => "Essentials.Sessions";

        private SessionProvider? _provider;

        /*
         * Declare a service configuration method to 
         * expose the session provider
         */

        [ServiceConfigurator]
        public void ConfigureServices(IServiceContainer services)
        {
            //publish the service
            services.AddService(typeof(ISessionProvider), _provider);
        }
       

        protected override void OnLoad()
        {
            List<RuntimeSessionProvider> providers = new();

            try
            {
                Log.Verbose("Loading all specified session providers");

                //Get all provider names
                IEnumerable<string> providerAssemblyNames = PluginConfig.GetProperty("provider_assemblies")
                                                .EnumerateArray()
                                                .Where(s => s.GetString() != null)
                                                .Select(s => s.GetString()!);

                
               
                foreach(string asm in providerAssemblyNames)
                {
                    Log.Verbose("Loading {dll} session provider", asm);
    
                    //Attempt to load provider
                    AssemblyLoader<ISessionProvider> prov =  this.LoadAssembly<ISessionProvider>(asm);

                    try
                    {
                        //Create localized log
                        LocalizedLogProvider log = new(Log, $"{Path.GetFileName(asm)}");

                        RuntimeSessionProvider p = new(prov);

                        //Call load method
                        p.Load(this, log);

                        //Add to list
                        providers.Add(p);
                    }
                    catch
                    {
                        prov.Dispose();
                        throw;
                    }
                }

                if(providers.Count > 0)
                {
                    //Create array for searching for providers
                    _provider = new(providers.ToArray());

                    Log.Information("Loaded {count} session providers", providers.Count);
                }
                else
                {
                    Log.Information("No session providers loaded");
                }

                Log.Information("Plugin loaded");
            }
            catch
            {
                //Dispose providers
                providers.ForEach(static s => s.Dispose());
                throw;
            }
        }
      
        protected override void OnUnLoad()
        {
            Log.Information("Plugin unloaded");
        }

        protected override void ProcessHostCommand(string cmd)
        {
            if (!this.IsDebug())
            {
                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());
            }
        }
    }
}