aboutsummaryrefslogtreecommitdiff
path: root/lib/Plugins.Essentials.ServiceStack/src/PluginStackInitializer.cs
blob: e6489c922379a3f9a9e4737342aacf5731980f7a (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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
* Copyright (c) 2024 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials.ServiceStack
* File: PluginStackInitializer.cs 
*
* PluginStackInitializer.cs is part of VNLib.Plugins.Essentials.ServiceStack which 
* is part of the larger VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials.ServiceStack 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 2 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Essentials.ServiceStack 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.Diagnostics;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.ComponentModel.Design;

using VNLib.Utils.Logging;
using VNLib.Plugins.Runtime;
using VNLib.Utils.Extensions;
using VNLib.Plugins.Runtime.Services;

namespace VNLib.Plugins.Essentials.ServiceStack
{

    internal sealed record class PluginStackInitializer(PluginLoadEventListener Listener, IPluginStack Stack, IManualPlugin[] ManualPlugins, bool ConcurrentLoad) 
        : IPluginInitializer
    {
        private readonly LinkedList<IManagedPlugin> _managedPlugins = new();
        private readonly LinkedList<ManualPluginWrapper> _manualPlugins = new();
       
        private void PrepareStack()
        {
            /*
            * Since we own the plugin stack, it is safe to build it here.
            * This method is not public and should not be called more than 
            * once. Otherwise it can cause issues with the plugin stack.
            */
            Stack.BuildStack();

            //Create plugin wrappers from loaded plugins
            ManagedPlugin[] wrapper = Stack.Plugins.Select(static p => new ManagedPlugin(p)).ToArray();

            //Add wrappers to list of managed plugins
            Array.ForEach(wrapper, p => _managedPlugins.AddLast(p));

            //Register for all plugins and pass the plugin instance as the state object
            Array.ForEach(wrapper, p => p.Plugin.Controller.Register(Listener, p));

            //Add manual plugins to list of managed plugins
            Array.ForEach(ManualPlugins, p => _manualPlugins.AddLast(new ManualPluginWrapper(p)));
        }

        ///<inheritdoc/>
        public IManagedPlugin[] InitializePluginStack(ILogProvider debugLog)
        {
            //Prepare the plugin stack before initializing
            PrepareStack();

            //single thread initialziation
            LinkedList<IManagedPlugin> _loadedPlugins = new();

            //Combine all managed plugins and initialize them individually
            IEnumerable<IManagedPlugin> plugins = _managedPlugins.Union(_manualPlugins);

            foreach(IManagedPlugin p in plugins)
            {
                //Try init plugin and add it to the list of loaded plugins
                if (InitializePluginCore(p, debugLog))
                {
                    _loadedPlugins.AddLast(p);
                }
            }

            /*
             * Load stage, load only initialized plugins.
             * 
             * Optionally single-threaded or parallel
             */

            if (ConcurrentLoad)
            {
                Parallel.ForEach(_loadedPlugins, wp => LoadPlugin(wp, debugLog));
            }
            else
            {
                _loadedPlugins.TryForeach(_loadedPlugins => LoadPlugin(_loadedPlugins, debugLog));
            }

            return _loadedPlugins.ToArray();
        }

        ///<inheritdoc/>
        public void UnloadPlugins()
        {
            Stack.UnloadAll();

            //Unload manual plugins in listener
            _managedPlugins.TryForeach(mp => Listener.OnPluginUnloaded(mp));
            _manualPlugins.TryForeach(static mp => mp.Unload());
        }

        ///<inheritdoc/>
        public void ReloadPlugins()
        {
            Stack.ReloadAll();

            //Unload manual plugins in listener, then call the unload method
            _managedPlugins.TryForeach(mp => Listener.OnPluginUnloaded(mp));
            _manualPlugins.TryForeach(static mp => mp.Unload());

            //Load, then invoke on-loaded events 
            _manualPlugins.TryForeach(static mp => mp.Load());
            _managedPlugins.TryForeach(mp => Listener.OnPluginLoaded(mp));
        }

        ///<inheritdoc/>
        public void Dispose()
        {
            Stack.Dispose();
            _manualPlugins.TryForeach(static mp => mp.Dispose());
            _manualPlugins.Clear();
        }

        private static bool InitializePluginCore(IManagedPlugin plugin, ILogProvider debugLog)
        {
            try
            {
                if (plugin is ManagedPlugin mp)
                {
                    //Initialzie plugin wrapper
                    mp.Plugin.InitializeController();

                    /*
                     * If the plugin assembly does not expose any plugin types or there is an issue loading the assembly, 
                     * its types my not unify, then we should give the user feedback insead of a silent fail.
                     */
                    if (!mp.Plugin.Controller.Plugins.Any())
                    {
                        debugLog.Warn("No plugin instances were exposed via {asm} assembly. This may be due to an assebmly mismatch", plugin.ToString());
                    }
                }
                else if(plugin is ManualPluginWrapper mpw)
                {
                    //Initialzie plugin wrapper
                    mpw.Plugin.Initialize();
                }
                else
                {
                    Debug.Fail("Missed managed plugin wrapper type");
                }

                return true;
            }
            catch (Exception ex)
            {
                debugLog.Error("Exception raised during initialzation of {asm}. It has been removed from the collection\n{ex}", plugin.ToString(), ex);
            }

            return false;
        }

        private void LoadPlugin(IManagedPlugin plugin, ILogProvider debugLog)
        {
            Stopwatch sw = new();
            try
            {
                sw.Start();

                //Recover the base class used to load instances 
                if (plugin is ManagedPlugin mp)
                {
                    mp.Plugin.LoadPlugins();
                }
                else if (plugin is ManualPluginWrapper mpw)
                {
                    mpw.Load();
                    //Call the on-load event in listener explicitly
                    Listener.OnPluginLoaded(plugin);
                }
                else
                {
                    Debug.Fail("Missed managed plugin wrapper type");
                }

                sw.Stop();

                debugLog.Verbose("Loaded {pl} in {tm} ms", plugin.ToString(), sw.ElapsedMilliseconds);
            }
            catch (Exception ex)
            {
                debugLog.Error("Exception raised during loading {asf}. Failed to load plugin \n{ex}", plugin.ToString(), ex);
            }
            finally
            {
                sw.Stop();
            }
        }


        private sealed record class ManagedPlugin(RuntimePluginLoader Plugin) : IManagedPlugin
        {
            private ServiceContainer? _services;

            ///<inheritdoc/>
            public IServiceContainer Services
            {
                get
                {
                    _ = _services ?? throw new InvalidOperationException("The service container is not currently loaded");
                    return _services!;
                }
            }

            /*
            * Automatically called after the plugin has successfully loaded
            * by event handlers below
            */

            ///<inheritdoc/>
            void IManagedPlugin.OnPluginLoaded()
            {
                //If the service container is defined, dispose
                _services?.Dispose();

                //Init new service container
                _services = new();

                //Get all exported services and add them to the container
                PluginServiceExport[] exports = Plugin.Controller.GetExportedServices();
                Array.ForEach(exports, e => _services.AddService(e.ServiceType, e.Service, true));
            }

            ///<inheritdoc/>
            void IManagedPlugin.OnPluginUnloaded()
            {
                //Cleanup services no longer in use. Plugin is still valid until this method returns
                _services?.Dispose();

                //Remove ref to services
                _services = null;
            }

            ///<inheritdoc/>
            bool IManagedPlugin.SendCommandToPlugin(string pluginName, string command, StringComparison comp)
            {
                //Get plugin
                LivePlugin? plugin = Plugin.Controller.Plugins.FirstOrDefault(p => p.PluginName.Equals(pluginName, comp));

                //If plugin is null, return false
                if (plugin == null)
                {
                    return false;
                }

                return plugin.SendConsoleMessage(command);
            }

            public override string ToString() => Path.GetFileName(Plugin.Config.AssemblyFile);
        }

        private sealed record class ManualPluginWrapper(IManualPlugin Plugin) : IManagedPlugin, IDisposable
        {
            private ServiceContainer _container = new();

            ///<inheritdoc/>
            public IServiceContainer Services => _container;

            public void Load()
            {
                Plugin.Load();
                Plugin.GetAllExportedServices(Services);
            }

            public void Unload()
            {
                Plugin.Unload();

                //Unload and re-init container
                _container.Dispose();
                _container = new();
            }

            public void Dispose()
            {
                //Dispose container
                _container.Dispose();

                //Dispose plugin
                Plugin.Dispose();
            }

            ///<inheritdoc/>
            bool IManagedPlugin.SendCommandToPlugin(string pluginName, string command, StringComparison comp)
            {

                if (Plugin.Name.Equals(pluginName, comp))
                {
                    Plugin.OnConsoleCommand(command);
                    return true;
                }

                return false;
            }
          
            void IManagedPlugin.OnPluginLoaded() 
            { }

            void IManagedPlugin.OnPluginUnloaded()
            { }

            ///<inheritdoc/>
            public override string ToString() => Plugin.Name;
        }

    }
}