aboutsummaryrefslogtreecommitdiff
path: root/lib/VNLib.Plugins.Extensions.Loading/src/ConfigurationExtensions.cs
blob: adfd997bff3e20c19b578d3082154f86e5c9f791 (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
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Extensions.Loading
* File: ConfigurationExtensions.cs 
*
* ConfigurationExtensions.cs is part of VNLib.Plugins.Extensions.Loading which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Extensions.Loading 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.Extensions.Loading 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.Text.Json;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

using VNLib.Utils.Extensions;

namespace VNLib.Plugins.Extensions.Loading
{
    /// <summary>
    /// Specifies a configuration variable name in the plugin's configuration 
    /// containing data specific to the type
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public sealed class ConfigurationNameAttribute : Attribute
    {
        /// <summary>
        /// 
        /// </summary>
        public string ConfigVarName { get; }

        /// <summary>
        /// Initializes a new <see cref="ConfigurationNameAttribute"/>
        /// </summary>
        /// <param name="configVarName">The name of the configuration variable for the class</param>
        public ConfigurationNameAttribute(string configVarName)
        {
            ConfigVarName = configVarName;
        }

        /// <summary>
        /// When true or not configured, signals that the type requires a configuration scope
        /// when loaded. When false, and configuration is not found, signals to the service loading
        /// system to continue without configuration
        /// </summary>
        public bool Required { get; init; } = true;
    }

    /// <summary>
    /// Contains extensions for plugin configuration specifc extensions
    /// </summary>
    public static class ConfigurationExtensions
    {
        public const string S3_CONFIG = "s3_config";
        public const string S3_SECRET_KEY = "s3_secret";
        public const string PLUGIN_ASSET_KEY = "assets";
        public const string PLUGINS_HOST_KEY = "plugins";
        public const string PLUGIN_PATH_KEY = "path";

        /// <summary>
        /// Retrieves a top level configuration dictionary of elements for the specified type.
        /// The type must contain a <see cref="ConfigurationNameAttribute"/>
        /// </summary>
        /// <typeparam name="T">The type to get the configuration of</typeparam>
        /// <param name="plugin"></param>
        /// <returns>A <see cref="Dictionary{TKey, TValue}"/> of top level configuration elements for the type</returns>
        /// <exception cref="KeyNotFoundException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        public static IConfigScope GetConfigForType<T>(this PluginBase plugin)
        {
            Type t = typeof(T);
            return plugin.GetConfigForType(t);
        }

        /// <summary>
        /// Retrieves a top level configuration dictionary of elements with the specified property name.
        /// </summary>
        /// <remarks>
        /// Search order: Plugin config, fall back to host config, throw if not found
        /// </remarks>
        /// <param name="plugin"></param>
        /// <param name="propName">The config property name to retrieve</param>
        /// <returns>A <see cref="IConfigScope"/> of top level configuration elements for the type</returns>
        /// <exception cref="KeyNotFoundException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        public static IConfigScope GetConfig(this PluginBase plugin, string propName)
        {
            plugin.ThrowIfUnloaded();
            try
            {
                //Try to get the element from the plugin config first
                if (!plugin.PluginConfig.TryGetProperty(propName, out JsonElement el))
                {
                    //Fallback to the host config
                    el = plugin.HostConfig.GetProperty(propName);
                }
                //Get the top level config as a dictionary
                return new ConfigScope(el, propName);
            }
            catch (KeyNotFoundException)
            {
                throw new KeyNotFoundException($"Missing required top level configuration object '{propName}', in host/plugin configuration files");
            }
        }

        /// <summary>
        /// Retrieves a top level configuration dictionary of elements with the specified property name,
        /// or null if no configuration could be found
        /// </summary>
        /// <remarks>
        /// Search order: Plugin config, fall back to host config, null not found
        /// </remarks>
        /// <param name="plugin"></param>
        /// <param name="propName">The config property name to retrieve</param>
        /// <returns>A <see cref="Dictionary{TKey, TValue}"/> of top level configuration elements for the type</returns>
        /// <exception cref="ObjectDisposedException"></exception>
        public static IConfigScope? TryGetConfig(this PluginBase plugin, string propName)
        {
            plugin.ThrowIfUnloaded();
            //Try to get the element from the plugin config first, or fallback to host
            if (plugin.PluginConfig.TryGetProperty(propName, out JsonElement el) 
                || plugin.HostConfig.TryGetProperty(propName, out el))
            {
                //Get the top level config as a dictionary
                return new ConfigScope(el, propName);
            }
            //No config found
            return null;
        }

        /// <summary>
        /// Retrieves a top level configuration dictionary of elements for the specified type.
        /// The type must contain a <see cref="ConfigurationNameAttribute"/>
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="type">The type to get configuration data for</param>
        /// <returns>A <see cref="IConfigScope"/> of top level configuration elements for the type</returns>
        /// <exception cref="ObjectDisposedException"></exception>
        public static IConfigScope GetConfigForType(this PluginBase plugin, Type type)
        {
            _ = type ?? throw new ArgumentNullException(nameof(type));

            string? configName = GetConfigNameForType(type);

            if (configName == null)
            {
                ThrowConfigNotFoundForType(type);
            }

            return plugin.GetConfig(configName);
        }

        /// <summary>
        /// Gets the configuration property name for the type
        /// </summary>
        /// <param name="type">The type to get the configuration name for</param>
        /// <returns>The configuration property element name</returns>
        public static string? GetConfigNameForType(Type type)
        {
            //Get config name attribute from plugin type
            return type.GetCustomAttribute<ConfigurationNameAttribute>()?.ConfigVarName;
        }

        /// <summary>
        /// Determines if the type requires a configuration element.
        /// </summary>
        /// <param name="type">The type to determine config required status</param>
        /// <returns>
        /// True if the configuration is required, or false if the <see cref="ConfigurationNameAttribute"/> 
        /// was not declared, or <see cref="ConfigurationNameAttribute.Required"/> is false
        /// </returns>
        public static bool ConfigurationRequired(Type type)
        {
            return type.GetCustomAttribute<ConfigurationNameAttribute>()?.Required ?? false;
        }

        /// <summary>
        /// Throws a <see cref="KeyNotFoundException"/> with proper diagnostic information
        /// for missing configuration for a given type
        /// </summary>
        /// <param name="type">The type to raise exception for</param>
        /// <exception cref="KeyNotFoundException"></exception>
        [DoesNotReturn]
        public static void ThrowConfigNotFoundForType(Type type)
        {
            //Try to get the config property name for the type
            string? configName = GetConfigNameForType(type);
            if (configName != null)
            {
                throw new KeyNotFoundException($"Missing required configuration key '{configName}' for type {type.Name}");
            }
            else
            {
                throw new KeyNotFoundException($"Missing required configuration key for type {type.Name}");
            }
        }

        /// <summary>
        /// Shortcut extension for <see cref="GetConfigForType{T}(PluginBase)"/> to get 
        /// config of current class
        /// </summary>
        /// <param name="obj">The object that a configuration can be retrieved for</param>
        /// <param name="plugin">The plugin containing configuration variables</param>
        /// <returns>A <see cref="IConfigScope"/> of top level configuration elements for the type</returns>
        /// <exception cref="ObjectDisposedException"></exception>
        public static IConfigScope GetConfig(this PluginBase plugin, object obj)
        {
            Type t = obj.GetType();
            return plugin.GetConfigForType(t);
        }

        /// <summary>
        /// Deserialzes the configuration to the desired object and calls its
        /// <see cref="IOnConfigValidation.Validate"/> method. Validation exceptions 
        /// are wrapped in a <see cref="ConfigurationValidationException"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="scope"></param>
        /// <returns></returns>
        /// <exception cref="ConfigurationValidationException"></exception>
        public static T DeserialzeAndValidate<T>(this IConfigScope scope) where T : IOnConfigValidation
        {
            T conf = scope.Deserialze<T>();
            try
            {
                conf.Validate();
            }
            catch(Exception ex)
            {
                throw new ConfigurationValidationException($"Configuration validation failed for type {typeof(T).Name}", ex);
            }
            return conf;
        }

        /// <summary>
        /// Determines if the current plugin configuration contains the require properties to initialize 
        /// the type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="plugin"></param>
        /// <returns>True if the plugin config contains the require configuration property</returns>
        public static bool HasConfigForType<T>(this PluginBase plugin) 
        {
            Type type = typeof(T);
            ConfigurationNameAttribute? configName = type.GetCustomAttribute<ConfigurationNameAttribute>();
            //See if the plugin contains a configuration varables
            return configName != null && (   
                    plugin.PluginConfig.TryGetProperty(configName.ConfigVarName, out _) ||
                    plugin.HostConfig.TryGetProperty(configName.ConfigVarName, out _)
                );
        }

        /// <summary>
        /// Gets a given configuration element from the global configuration scope
        /// and deserializes it into the desired type. 
        /// <para>
        /// If the type inherits <see cref="IOnConfigValidation"/> the <see cref="IOnConfigValidation.Validate"/>
        /// method is invoked, and exceptions are warpped in <see cref="ConfigurationValidationException"/>
        /// </para>
        /// <para>
        /// If the type inherits <see cref="IAsyncConfigurable"/> the <see cref="IAsyncConfigurable.ConfigureServiceAsync(PluginBase)"/>
        /// method is called by the service scheduler
        /// </para>
        /// </summary>
        /// <typeparam name="TConfig">The configuration type</typeparam>
        /// <param name="plugin"></param>
        /// <returns>The deserialzed configuration element</returns>
        /// <exception cref="ConfigurationValidationException"></exception>
        public static TConfig GetConfigElement<TConfig>(this PluginBase plugin)
        {
            //Deserialze the element
            TConfig config = plugin.GetConfigForType<TConfig>().Deserialze<TConfig>();

            //If the type is validatable, validate it
            if(config is IOnConfigValidation conf)
            {
                try
                {
                    conf.Validate();
                }
                catch (Exception ex)
                {
                    throw new ConfigurationValidationException($"Configuration validation failed for type {typeof(TConfig).Name}", ex);
                }
            }

            //If async config, load async
            if(config is IAsyncConfigurable ac)
            {
                _ = plugin.ConfigureServiceAsync(ac);
            }

            return config;
        }

        /// <summary>
        /// Gets a given configuration element from the global configuration scope
        /// and deserializes it into the desired type. 
        /// <para>
        /// If the type inherits <see cref="IOnConfigValidation"/> the <see cref="IOnConfigValidation.Validate"/>
        /// method is invoked, and exceptions are warpped in <see cref="ConfigurationValidationException"/>
        /// </para>
        /// <para>
        /// If the type inherits <see cref="IAsyncConfigurable"/> the <see cref="IAsyncConfigurable.ConfigureServiceAsync(PluginBase)"/>
        /// method is called by the service scheduler
        /// </para>
        /// </summary>
        /// <typeparam name="TConfig">The configuration type</typeparam>
        /// <param name="plugin"></param>
        /// <param name="elementName">The configuration element name override</param>
        /// <returns>The deserialzed configuration element</returns>
        /// <exception cref="ConfigurationValidationException"></exception>
        public static TConfig GetConfigElement<TConfig>(this PluginBase plugin, string elementName)
        {
            //Deserialze the element
            TConfig config = plugin.GetConfig(elementName).Deserialze<TConfig>();

            //If the type is validatable, validate it
            if (config is IOnConfigValidation conf)
            {
                try
                {
                    conf.Validate();
                }
                catch (Exception ex)
                {
                    throw new ConfigurationValidationException($"Configuration validation failed for type {typeof(TConfig).Name}", ex);
                }
            }

            //If async config, load async
            if (config is IAsyncConfigurable ac)
            {
                _ = plugin.ConfigureServiceAsync(ac);
            }

            return config;
        }


        /// <summary>
        /// Attempts to load the basic S3 configuration variables required
        /// for S3 client access
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns>The S3 configuration object found in the plugin/host configuration</returns>
        public static S3Config? TryGetS3Config(this PluginBase plugin)
        {
            //Try get the config
            IConfigScope? s3conf = plugin.TryGetConfig(S3_CONFIG);
            return s3conf?.Deserialze<S3Config>();
        }

        /// <summary>
        /// Trys to get the optional assets directory from the plugin configuration
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns>The absolute path to the assets directory if defined, null otherwise</returns>
        public static string? GetAssetsPath(this PluginBase plugin)
        { 
            //Get global plugin config element
            IConfigScope config = plugin.GetConfig(PLUGINS_HOST_KEY);

            //Try to get the assets path if its defined
            string? assetsPath = config.GetPropString(PLUGIN_ASSET_KEY);

            //Try to get the full path for the assets if we can
            return assetsPath != null ? Path.GetFullPath(assetsPath) : null;
        }

        /// <summary>
        /// Gets the absolute path to the plugins directory as defined in the host configuration
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns>The absolute path to the directory containing all plugins</returns>
        public static string GetPluginsPath(this PluginBase plugin)
        {
            //Get global plugin config element
            IConfigScope config = plugin.GetConfig(PLUGINS_HOST_KEY);

            //Get the plugins path or throw because it should ALWAYS be defined if this method is called
            string pluginsPath = config[PLUGIN_PATH_KEY].GetString()!;

            //Get absolute path
            return Path.GetFullPath(pluginsPath);
        }
    }
}