aboutsummaryrefslogtreecommitdiff
path: root/lib/Plugins.Runtime/src/PluginController.cs
blob: 7f82c13dc226fb156ed59471c7d97e9348865262 (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
/*
* Copyright (c) 2024 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Runtime
* File: PluginController.cs 
*
* PluginController.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.Linq;
using System.Reflection;
using System.Collections.Generic;

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

namespace VNLib.Plugins.Runtime
{

    /// <summary>
    /// Manages the lifetime of a collection of <see cref="IPlugin"/> instances,
    /// and their dependent event listeners
    /// </summary>
    public sealed class PluginController : IPluginEventRegistrar
    {
        /*
         * Lock must be held any time the internals lists are read/written
         * to avoid read/write enumeration issues.
         * 
         * This can happen when a manual unload is called duiring an automatic 
         * reload, or a runtime is tearing down the plugin environment 
         * when an automatic reload is happening.
         * 
         * This also allows thread safe register/unregister event listeners
         */
        private readonly object _stateLock = new();

        private readonly List<LivePlugin> _plugins;
        private readonly List<KeyValuePair<IPluginEventListener, object?>> _listeners;
        private readonly PluginServicePool _servicePool;
     

        internal PluginController()
        {
            _plugins = new ();
            _listeners = new ();
            _servicePool = new ();
        }

        /// <summary>
        /// The current collection of plugins. Valid before the unload event.
        /// </summary>
        public IEnumerable<LivePlugin> Plugins => _plugins;     

        ///<inheritdoc/>
        ///<exception cref="ArgumentNullException"></exception>
        public void Register(IPluginEventListener listener, object? state = null)
        {
            _ = listener ?? throw new ArgumentNullException(nameof(listener));

            lock (_stateLock)
            {
                _listeners.Add(new(listener, state));
            }
        }

        ///<inheritdoc/>
        public bool Unregister(IPluginEventListener listener)
        {
            lock(_stateLock)
            {
                //Remove listener
                return _listeners.RemoveAll(p => p.Key == listener) > 0;
            }
        }

        /// <summary>
        /// Populates the given <see cref="IServiceContainer"/> with all services
        /// </summary>
        public PluginServiceExport[] GetExportedServices() => _servicePool.GetServices();

        internal void InitializePlugins(Assembly asm)
        {
            lock (_stateLock)
            {
                //get all Iplugin types
                Type[] types = asm.GetTypes().Where(static type => !type.IsAbstract && typeof(IPlugin).IsAssignableFrom(type)).ToArray();

                //Initialize the new plugin instances
                IPlugin[] plugins = types.Select(static t => (IPlugin)Activator.CreateInstance(t)!).ToArray();

                //Crate new containers
                LivePlugin[] lps = plugins.Select(p => new LivePlugin(p, asm)).ToArray();

                //Store containers
                _plugins.AddRange(lps);
            }
        }

        internal void ConfigurePlugins(VnMemoryStream configData, string[] cliArgs)
        {
            lock (_stateLock)
            {
                _plugins.TryForeach(lp => lp.InitConfig(configData.AsSpan()));
                _plugins.TryForeach(lp => lp.InitLog(cliArgs));
            }
        }

        internal void LoadPlugins()
        {
            lock( _stateLock)
            {
                //Load all plugins
                _plugins.TryForeach(static p => p.LoadPlugin());

                //Load all services into the service pool
                _plugins.TryForeach(p => p.GetServices(_servicePool));

                //Notify event handlers
                _listeners.TryForeach(l => l.Key.OnPluginLoaded(this, l.Value));
            }
        }

        internal void UnloadPlugins()
        {
            lock (_stateLock)
            {
                try
                {
                    //Notify event handlers
                    _listeners.TryForeach(l => l.Key.OnPluginUnloaded(this, l.Value));

                    //Unload plugin instances
                    _plugins.TryForeach(static p => p.UnloadPlugin());
                }
                finally
                {
                    //Always clear plugins
                    _plugins.Clear();
                    //always make sure service pool is clear
                    _servicePool.Clear();
                }
            }
        }

        internal void Dispose()
        {
            _plugins.Clear();
            _listeners.Clear();
            _servicePool.Clear();
        }

    }
}