aboutsummaryrefslogtreecommitdiff
path: root/lib/Plugins.Runtime/src/LoaderExtensions.cs
blob: c553f4b3b6511a6fe52e4c01e21664edfc261896 (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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Runtime
* File: LoaderExtensions.cs 
*
* LoaderExtensions.cs is part of VNLib.Plugins.Runtime which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Runtime is free software: you can redistribute it and/or modify 
* it under the terms of the GNU 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.Runtime 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 
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License 
* along with VNLib.Plugins.Runtime. If not, see http://www.gnu.org/licenses/.
*/

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;

using VNLib.Utils.IO;
using VNLib.Utils.Extensions;

namespace VNLib.Plugins.Runtime
{
    /// <summary>
    /// Contains extension methods for PluginLoader library
    /// </summary>
    public static class LoaderExtensions
    {
        /*
         * Class that manages a collection registration for a specific type 
         * dependency, and redirects the event calls for the consumed service
         */
        private sealed class TypedRegistration<T> : IPluginEventListener where T: class
        {
            private readonly ITypedPluginConsumer<T> _consumerEvents;
            private readonly object? _userState;

            private T? _service;
            private readonly Type _type;

            public TypedRegistration(ITypedPluginConsumer<T> consumerEvents, Type type)
            {
                _consumerEvents = consumerEvents;
                _type = type;
            }
            

            public void OnPluginLoaded(PluginController controller, object? state)
            {
                //Get the service from the loaded plugins
                T service = controller.Plugins
                    .Where(pl => _type.IsAssignableFrom(pl.PluginType))
                    .Select(static pl => (T)pl.Plugin!)
                    .First();

                //Call load with the exported type
                _consumerEvents.OnLoad(service, _userState);

                //Store for unload
                _service = service;
            }

            public void OnPluginUnloaded(PluginController controller, object? state)
            {
                //Unload
                _consumerEvents.OnUnload(_service!, _userState);
                _service = null;
            }
        }

        /// <summary>
        /// Registers a plugin even handler for the current <see cref="PluginController"/>
        /// for a specific type. 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <param name="consumer">The typed plugin instance event consumer</param>
        /// <returns>A <see cref="PluginEventRegistration"/> handle that manages this event registration</returns>
        /// <exception cref="ArgumentException"></exception>
        public static PluginEventRegistration RegisterForType<T>(this PluginController collection, ITypedPluginConsumer<T> consumer) where T: class
        {
            Type serviceType = typeof(T);

            //Confim the type is exposed by this collection
            if(!ExposesType(collection, serviceType))
            {
                throw new ArgumentException("The requested type is not exposed in this assembly");
            }

            //Create new typed listener
            TypedRegistration<T> reg = new(consumer, serviceType);

            //register event handler
            return Register(collection, reg, null);
        }

        /// <summary>
        /// Registers a handler to listen for plugin load/unload events
        /// </summary>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>A <see cref="PluginEventRegistration"/> handle that will unregister the listener when disposed</returns>
        public static PluginEventRegistration Register(this IPluginEventRegistrar reg, IPluginEventListener listener, object? state = null)
        {
            reg.Register(listener, state);
            return new(reg, listener);
        }
       
        /// <summary>
        /// Determines if the current <see cref="PluginController"/>
        /// exposes the desired type on is <see cref="IPlugin"/>
        /// type.
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="type">The desired type to request</param>
        /// <returns>True if the plugin exposes the desired type, false otherwise</returns>
        public static bool ExposesType(this PluginController collection, Type type)
        {
            return collection.Plugins
                .Where(pl => type.IsAssignableFrom(pl.PluginType))
                .Any();
        }

        /// <summary>
        /// Searches all plugins within the current loader for a 
        /// single plugin that derrives the specified type
        /// </summary>
        /// <typeparam name="T">The type the plugin must derrive from</typeparam>
        /// <param name="collection"></param>
        /// <returns>The instance of your custom type casted, or null if not found or could not be casted</returns>
        public static T? GetExposedTypes<T>(this PluginController collection) where T: class
        {
            LivePlugin? plugin = collection.Plugins
                .Where(static pl => typeof(T).IsAssignableFrom(pl.PluginType))
                .SingleOrDefault();

            return plugin?.Plugin as T;
        }

        /// <summary>
        /// Serially initialzies all plugin lifecycle controllers and configures 
        /// plugin instances.
        /// </summary>
        /// <param name="runtime"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void InitializeAll(this IPluginStack runtime)
        {
            _ = runtime ?? throw new ArgumentNullException(nameof(runtime));

            foreach(RuntimePluginLoader loader in runtime.Plugins)
            {
                loader.InitializeController();
            }
        }

        /// <summary>
        /// Invokes the load method for all plugin instances
        /// </summary>
        /// <param name="runtime"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="AggregateException"></exception>
        public static void InvokeLoad(this IPluginStack runtime)
        {
            _ = runtime ?? throw new ArgumentNullException(nameof(runtime));

            //try loading all plugins
            runtime.Plugins.TryForeach(static p => p.LoadPlugins());
        }

        /// <summary>
        /// Invokes the unload method for all plugin instances
        /// </summary>
        /// <param name="runtime"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="AggregateException"></exception>
        public static void InvokeUnload(this IPluginStack runtime)
        {
            _ = runtime ?? throw new ArgumentNullException(nameof(runtime));

            //try unloading all plugins
            runtime.Plugins.TryForeach(static p => p.UnloadPlugins());
        }

        /// <summary>
        /// Unloads all plugins and the plugin assembly loader
        /// if unloading is supported.
        /// </summary>
        /// <param name="runtime"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="AggregateException"></exception>
        public static void UnloadAll(this IPluginStack runtime)
        {
            _ = runtime ?? throw new ArgumentNullException(nameof(runtime));

            //try unloading all plugins and their loaders
            runtime.Plugins.TryForeach(static p => p.UnloadAll());
        }

        /// <summary>
        /// Reloads all plugins and each assembly loader
        /// </summary>
        /// <param name="runtime"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="AggregateException"></exception>
        public static void ReloadAll(this IPluginStack runtime)
        {
            _ = runtime ?? throw new ArgumentNullException(nameof(runtime));

            //try reloading all plugins
            runtime.Plugins.TryForeach(static p => p.ReloadPlugins());
        }

        /// <summary>
        /// Registers a plugin event listener for all plugins
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="listener">The event listener instance</param>
        /// <param name="state">Optional state parameter</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void RegsiterListener(this IPluginStack runtime, IPluginEventListener listener, object? state = null)
        {
            _ = runtime ?? throw new ArgumentNullException(nameof(runtime));
            _ = listener ?? throw new ArgumentNullException(nameof(listener));

            //Register for all plugins
            foreach (PluginController controller in runtime.Plugins.Select(static p => p.Controller))
            {
                controller.Register(listener, state);
            }
        }

        /// <summary>
        /// Unregisters a plugin event listener for all plugins
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="listener">The listener instance to unregister</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void UnregsiterListener(this IPluginStack runtime, IPluginEventListener listener)
        {
            _ = runtime ?? throw new ArgumentNullException(nameof(runtime));
            _ = listener ?? throw new ArgumentNullException(nameof(listener));

            //Unregister for all plugins
            foreach (PluginController controller in runtime.Plugins.Select(static p => p.Controller))
            {
                controller.Unregister(listener);
            }
        }

        /// <summary>
        /// Configures the plugin stack to retrieve plugin-local json configuration files 
        /// from the same directory as the plugin assembly file.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="hostConfig">An optional configuration element to pass to the plugin's host config element</param>
        /// <returns>The current builder instance for chaining</returns>
        public static PluginStackBuilder WithLocalJsonConfig(this PluginStackBuilder builder, in JsonElement? hostConfig)
        {
            _ = builder ?? throw new ArgumentNullException(nameof(builder));

            LocalFilePluginConfigReader reader;

            //Host config is optional
            if (hostConfig.HasValue)
            {
                //Clone the host config into binary
                using VnMemoryStream ms = new();
                using (Utf8JsonWriter writer = new(ms))
                {
                    hostConfig.Value.WriteTo(writer);
                }

                //Create a reader from the binary
                reader = new LocalFilePluginConfigReader(ms.ToArray());
            }
            else
            {
                //Empty json
                byte[] emptyJson = Encoding.UTF8.GetBytes("{}");
                reader = new LocalFilePluginConfigReader(emptyJson);
            }

            //Store binary
            return builder.WithConfigurationReader(reader);
        }

        /// <summary>
        /// Specifies the directory that the plugin loader will search for plugins in
        /// </summary>
        /// <param name="path">The search directory path</param>
        /// <param name="builder"></param>
        /// <returns>The current builder instance for chaining</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static PluginStackBuilder WithSearchDirectory(this PluginStackBuilder builder, string path) => WithSearchDirectory(builder, new DirectoryInfo(path));

        /// <summary>
        /// Specifies the directory that the plugin loader will search for plugins in
        /// </summary>
        /// <param name="dir">The search directory instance</param>
        /// <param name="builder"></param>
        /// <returns>The current builder instance for chaining</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static PluginStackBuilder WithSearchDirectory(this PluginStackBuilder builder, DirectoryInfo dir)
        {
            _ = builder ?? throw new ArgumentNullException(nameof(builder));
            _ = dir ?? throw new ArgumentNullException(nameof(dir));

            PluginDirectorySearcher dirSearcher = new (dir);
            builder.WithDiscoveryManager(dirSearcher);
            return builder;
        }

        /// <summary>
        /// Gets the current collection of loaded plugins for the plugin stack
        /// </summary>
        /// <param name="stack"></param>
        /// <returns>An enumeration of all <see cref="LivePlugin"/> wrappers</returns>
        public static IEnumerable<LivePlugin> GetAllPlugins(this IPluginStack stack) => stack.Plugins.SelectMany(static p => p.Controller.Plugins);

        private sealed record class PluginDirectorySearcher(DirectoryInfo Dir) : IPluginDiscoveryManager
        {
            private const string PLUGIN_FILE_EXTENSION = ".dll";

            ///<inheritdoc/>
            public string[] DiscoverPluginFiles()
            {
                //Enumerate all dll files within the seach directory
                IEnumerable<DirectoryInfo> dirs = Dir.EnumerateDirectories("*", SearchOption.TopDirectoryOnly);

                //Search all directories for plugins and return the paths
                return GetPluginPaths(dirs).ToArray();
            }

            private static IEnumerable<string> GetPluginPaths(IEnumerable<DirectoryInfo> dirs)
            {
                //Select only dirs with a dll that is named after the directory name
                return dirs.Where(static pdir =>
                {
                    string compined = Path.Combine(pdir.FullName, pdir.Name);
                    string FilePath = string.Concat(compined, PLUGIN_FILE_EXTENSION);
                    return FileOperations.FileExists(FilePath);
                })
                //Return the name of the dll file to import
                .Select(static pdir =>
                {
                    string compined = Path.Combine(pdir.FullName, pdir.Name);
                    return string.Concat(compined, PLUGIN_FILE_EXTENSION);
                });
            }
        }

        /*
         * Assumes plugin configuration data is stored in a json file with the same name as 
         * the plugin assembly but with a json extension. 
         * 
         * The json file is local for the specific plugin and is not shared between plugins. The host 
         * configuration is also required
         */
        private sealed record class LocalFilePluginConfigReader(ReadOnlyMemory<byte> HostJson) : IPluginConfigReader
        {
            public void ReadPluginConfigData(IPluginAssemblyLoadConfig asmConfig, Stream configData)
            {
                //Allow comments and trailing commas
                JsonDocumentOptions jdo = new()
                {
                    AllowTrailingCommas = true,
                    CommentHandling = JsonCommentHandling.Skip,
                };

                //Config file is the same name as the assembly but with a json extension
                string pluginConfigFile = Path.ChangeExtension(asmConfig.AssemblyFile, ".json");

                using JsonDocument hConfig = JsonDocument.Parse(HostJson, jdo);

                //Read the plugin config file
                if (FileOperations.FileExists(pluginConfigFile))
                {
                    //Open file stream to read data
                    using FileStream confStream = File.OpenRead(pluginConfigFile);

                    //Parse the config file
                    using JsonDocument pConfig = JsonDocument.Parse(confStream, jdo);

                    //Merge the configs
                    using JsonDocument merged = hConfig.Merge(pConfig,"host", "plugin");

                    //Write the merged config to the output stream
                    using Utf8JsonWriter writer = new(configData);
                    merged.WriteTo(writer);
                }
                else
                {
                    byte[] pluginConfig = Encoding.UTF8.GetBytes("{}");

                    using JsonDocument pConfig = JsonDocument.Parse(pluginConfig, jdo);

                    //Merge the configs
                    using JsonDocument merged = hConfig.Merge(pConfig,"host", "plugin");

                    //Write the merged config to the output stream
                    using Utf8JsonWriter writer = new(configData);
                    merged.WriteTo(writer);
                }
            }
        }
    }
}