aboutsummaryrefslogtreecommitdiff
path: root/VNLib.Plugins.Extensions.Loading/RoutingExtensions.cs
blob: 3e539e3268612ec53948d0b5cfdb6417326c7103 (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
using System;
using System.Linq;
using System.Text.Json;
using System.Reflection;
using System.Collections.Generic;

using VNLib.Plugins.Extensions.Loading.Events;
using VNLib.Plugins.Extensions.Loading.Configuration;

namespace VNLib.Plugins.Extensions.Loading.Routing
{
    /// <summary>
    /// Provides advanced QOL features to plugin loading
    /// </summary>
    public static class RoutingExtensions
    { 
        /// <summary>
        /// Constructs and routes the specific endpoint type for the current plugin
        /// </summary>
        /// <typeparam name="T">The <see cref="IEndpoint"/> type</typeparam>
        /// <param name="plugin"></param>
        /// <param name="pluginConfigPathName">The path to the plugin sepcific configuration property</param>
        /// <exception cref="TargetInvocationException"></exception>
        public static T Route<T>(this PluginBase plugin, string? pluginConfigPathName) where T : IEndpoint
        {
            Type endpointType = typeof(T);
            try
            {
                //If the config attribute is not set, then ignore the config variables
                if (string.IsNullOrWhiteSpace(pluginConfigPathName))
                {
                    ConstructorInfo? constructor = endpointType.GetConstructor(new Type[] { typeof(PluginBase) });
                    _ = constructor ?? throw new EntryPointNotFoundException($"No constructor found for {endpointType.Name}");
                    //Create the new endpoint and pass the plugin instance
                    T endpoint = (T)constructor.Invoke(new object[] { plugin });
                    //Register event handlers for the endpoint
                    ScheduleIntervals(plugin, endpoint, endpointType, null);
                    //Route the endpoint
                    plugin.Route(endpoint);
                    return endpoint;
                }
                else
                {
                    ConstructorInfo? constructor = endpointType.GetConstructor(new Type[] { typeof(PluginBase), typeof(Dictionary<string, JsonElement>) });
                    //Make sure the constructor exists
                    _ = constructor ?? throw new EntryPointNotFoundException($"No constructor found for {endpointType.Name}");
                    //Get config variables for the endpoint
                    IReadOnlyDictionary<string, JsonElement> conf = plugin.GetConfig(pluginConfigPathName);
                    //Create the new endpoint and pass the plugin instance along with the configuration object
                    T endpoint = (T)constructor.Invoke(new object[] { plugin, conf });
                    //Register event handlers for the endpoint
                    ScheduleIntervals(plugin, endpoint, endpointType, conf);
                    //Route the endpoint
                    plugin.Route(endpoint);
                    return endpoint;
                }
            }
            catch (TargetInvocationException te) when (te.InnerException != null)
            {
                throw te.InnerException;
            }
        }

        /// <summary>
        /// Constructs and routes the specific endpoint type for the current plugin
        /// </summary>
        /// <typeparam name="T">The <see cref="IEndpoint"/> type</typeparam>
        /// <param name="plugin"></param>
        /// <exception cref="TargetInvocationException"></exception>
        public static T Route<T>(this PluginBase plugin) where T : IEndpoint
        {
            Type endpointType = typeof(T);
            //Get config name attribute
            ConfigurationNameAttribute? configAttr = endpointType.GetCustomAttribute<ConfigurationNameAttribute>();
            //Route using attribute
            return plugin.Route<T>(configAttr?.ConfigVarName);
        }

        private static void ScheduleIntervals<T>(PluginBase plugin, T endpointInstance, Type epType, IReadOnlyDictionary<string, JsonElement>? endpointLocalConfig) where T: IEndpoint
        {
            List<EventHandle> registered = new();
            try
            {
                //Get all methods that have the configureable async interval attribute specified
                IEnumerable<Tuple<ConfigurableAsyncIntervalAttribute, AsyncSchedulableCallback>> confIntervals = epType.GetMethods()
                    .Where(m => m.GetCustomAttribute<ConfigurableAsyncIntervalAttribute>() != null)
                    .Select(m => new Tuple<ConfigurableAsyncIntervalAttribute, AsyncSchedulableCallback>
                    (m.GetCustomAttribute<ConfigurableAsyncIntervalAttribute>()!, m.CreateDelegate<AsyncSchedulableCallback>(endpointInstance)));

                //If the endpoint has a local config, then use it to find the interval
                if (endpointLocalConfig != null)
                {

                    //Schedule event handlers on the current plugin
                    foreach (Tuple<ConfigurableAsyncIntervalAttribute, AsyncSchedulableCallback> interval in confIntervals)
                    {
                        int value = endpointLocalConfig[interval.Item1.IntervalPropertyName].GetInt32();
                        //Get the timeout from its resolution variable
                        TimeSpan timeout = interval.Item1.Resolution switch
                        {
                            IntervalResultionType.Seconds => TimeSpan.FromSeconds(value),
                            IntervalResultionType.Minutes => TimeSpan.FromMinutes(value),
                            IntervalResultionType.Hours => TimeSpan.FromHours(value),
                            _ => TimeSpan.FromMilliseconds(value),
                        };
                        //Schedule
                        registered.Add(plugin.ScheduleInterval(interval.Item2, timeout));
                    }
                }

                //Get all methods that have the async interval attribute specified
                IEnumerable<Tuple<AsyncIntervalAttribute, AsyncSchedulableCallback>> intervals = epType.GetMethods()
                    .Where(m => m.GetCustomAttribute<AsyncIntervalAttribute>() != null)
                    .Select(m => new Tuple<AsyncIntervalAttribute, AsyncSchedulableCallback>(
                        m.GetCustomAttribute<AsyncIntervalAttribute>()!, m.CreateDelegate<AsyncSchedulableCallback>(endpointInstance))
                    );

                //Schedule event handlers on the current plugin
                foreach (Tuple<AsyncIntervalAttribute, AsyncSchedulableCallback> interval in intervals)
                {
                    registered.Add(plugin.ScheduleInterval(interval.Item2, interval.Item1.Interval));
                }
            }
            catch
            {
                //Stop all event handles
                foreach(EventHandle evh in registered)
                {
                    evh.Dispose();
                }
                throw;
            }
        }
    }
}