-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathModuleHost.cs
More file actions
378 lines (324 loc) · 16 KB
/
ModuleHost.cs
File metadata and controls
378 lines (324 loc) · 16 KB
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
/*
The MIT License (MIT)
Copyright (c) 2025 John Earnshaw, NetModules Foundation.
Repository Url: https://github.com/netmodules/netmodules/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NetModules.Interfaces;
using NetModules.Classes;
using NetModules.Events;
namespace NetModules
{
/// <summary>
/// <see cref="ModuleHost"/> implements <see cref="IModuleHost"/> interface and is designed to be inherited in your own project.
/// Functionality is included to load modules from assemblies located within the <see cref="ModuleHost.WorkingDirectory"/> and
/// one level deep via <see cref="ModuleHost.Modules"/> <see cref="IModuleCollection.LoadModules(IList{ModuleName})"/>. It is
/// possible to implement your own <see cref="IModuleHost"/> or extend <see cref="ModuleHost"/> if required.
/// </summary>
public abstract class ModuleHost : IModuleHost
{
readonly ModuleCollection _ModuleCollection;
readonly EventCollection _EventCollection;
readonly Dictionary<string, IEvent> _EventsInProgress;
readonly ReadOnlyDictionary<string, IEvent> _ReadOnlyEventsInProgress;
/// <summary>
/// Creates a new instance of <see cref="ModuleHost"/>. When using startup args in your application, you can pass these args
/// through to <see cref="ModuleHost"/> so they can be inspected by any <see cref="Module"/> that may require them.
/// </summary>
/// <param name="args">Arguments to pass to modules.</param>
public ModuleHost(string[] args = null)
{
if (args != null)
{
Arguments = args;
}
else
{
Arguments = new List<string>();
}
var eventCollection = new EventCollection(this);
var moduleCollection = new ModuleCollection(this);
// Create the events tracking list and a readonly wrapper to pass in the IModuleHost.EventsInProgress property.
// We do this here since Host starts throwing a few LoggingEvent events into the system while importing and
// loading, etc...
_EventsInProgress = new Dictionary<string, IEvent>();
_ReadOnlyEventsInProgress = new ReadOnlyDictionary<string, IEvent>(_EventsInProgress);
eventCollection.ImportEvents();
moduleCollection.ImportModules();
_EventCollection = eventCollection;
_ModuleCollection = moduleCollection;
}
/// <summary>
/// Destroy.
/// </summary>
~ModuleHost()
{
Modules.UnloadModules(null);
}
/// <summary>
/// The <see cref="IModuleCollection"/> contains any discovered <see cref="Module"/> types and methods to invoke instances
/// of loaded modules.
/// </summary>
public virtual IModuleCollection Modules
{
get
{
return _ModuleCollection;
}
}
/// <summary>
/// The <see cref="IEventCollection"/> contains all known <see cref="IEvent"/> types and contains methods that can instantiate
/// them.
/// </summary>
public virtual IEventCollection Events
{
get
{
return _EventCollection;
}
}
/// <summary>
/// If any arguments are passed to the <see cref="ModuleHost"/> while invoking its constructor, these arguments will be added to
/// this property so that <see cref="Module"/> instances can inspect them for directives.
/// </summary>
public virtual IList<string> Arguments { get; } = new List<string>();
Uri _WorkingDirectory;
/// <summary>
/// Returns the system directory from where this <see cref="ModuleHost"/> instance is running. This is useful for loading other
/// resources or creating files and writing data alongside the <see cref="ModuleHost"/> instance.
/// </summary>
public virtual Uri WorkingDirectory
{
get
{
if (_WorkingDirectory == null)
{
_WorkingDirectory = AssemblyTools.GetPathToAssembly(GetType());
}
return _WorkingDirectory;
}
}
string _ApplicationName;
/// <summary>
/// Returns the invoking application name via <see cref="System.Reflection"/>.GetCallingAssembly().
/// </summary>
public virtual string ApplicationName
{
get
{
if (_ApplicationName == null)
{
_ApplicationName = System.Reflection.Assembly.GetCallingAssembly().GetName().Name;
}
return _ApplicationName;
}
}
/// <summary>
/// Any <see cref="IEvent"/> passed to <see cref="ModuleHost.Handle(IEvent)"/> will be added to this dictionary
/// and removed once it has been processed. This property allows other <see cref="IModule"/> instances to monitor
/// events within the system. Any ghost events will not be visible here. Ghos events are <see cref="IEvent"/>
/// instances that are passed to <see cref="Module.Handle(IEvent)"/> directly. Ghost events are not recommended.
/// </summary>
public virtual IReadOnlyDictionary<string, IEvent> EventsInProgress {
get
{
return _ReadOnlyEventsInProgress;
}
}
/// <summary>
/// <see cref="ModuleHost"/> implements <see cref="IEventHandler"/> and exposes its methods so that a <see cref="IModule"/>
/// instance can check to see if an <see cref="IEvent"/> instance can be handled and pass it to <see cref="ModuleHost.Handle(IEvent)"/>
/// for handling. It is recommended to always use <see cref="IModuleHost"/> to handle events rather than invoking
/// <see cref="Module.Handle(IEvent)"/> directly. Invoking <see cref="Module.Handle(IEvent)"/> will create a ghost event
/// that will be invisible to the current instance of <see cref="IModuleHost"/> and all other modules.
/// </summary>
public virtual bool CanHandle(IEvent e)
{
if (_ModuleCollection != null)
{
return _ModuleCollection.CanHandle(e);
}
return false;
}
/// <summary>
/// <see cref="ModuleHost"/> implements <see cref="IEventHandler"/> and exposes its methods so that a <see cref="IModule"/>
/// instance can check to see if an <see cref="IEvent"/> instance can be handled and pass it to <see cref="ModuleHost.Handle(IEvent)"/>
/// for handling. It is recommended to always use <see cref="IModuleHost"/> to handle events rather than invoking
/// <see cref="Module.Handle(IEvent)"/> directly. Invoking <see cref="Module.Handle(IEvent)"/> will create a ghost event
/// that will be invisible to the current instance of <see cref="IModuleHost"/> and all other modules.
/// </summary>
public virtual async Task<bool> CanHandleAsync(IEvent e)
{
return await Task.Run(() => CanHandle(e));
}
/// <summary>
/// <see cref="ModuleHost"/> implements <see cref="IEventHandler"/> and exposes its methods so that a <see cref="IModule"/>
/// instance can check to see if an <see cref="IEvent"/> instance can be handled and pass it to <see cref="ModuleHost.Handle(IEvent)"/>
/// for handling. It is recommended to always use <see cref="IModuleHost"/> to handle events rather than invoking
/// <see cref="Module.Handle(IEvent)"/> directly. Invoking <see cref="Module.Handle(IEvent)"/> will create a ghost event
/// that will be invisible to the <see cref="IModuleHost"/> and all other modules.
/// </summary>
public virtual void Handle(IEvent e)
{
// We don't want to do any trace logging here if the event type is LoggingEvent as this will
// cause a LoggingEvent trace loop (StackOverflowException)...
var isLoggingEvent = e is LoggingEvent;
if (!isLoggingEvent)
{
Log(LoggingEvent.Severity.Trace
, Constants._ModuleHostEventReceived
, e is ISensitiveEvent ? e.Name : e);
}
// We generate a unique ID for the event and add it to the IEvent.Meta dictionary. This unique ID can be used to
// Track and monitor the event during the handling process through the exposed EventsInProgress property.
var id = GenerateEventId(e);
e.SetMetaValueInternal(Constants._MetaId, id, false, true);
lock (_EventsInProgress)
{
_EventsInProgress.Add(id, e);
if (!isLoggingEvent)
{
Log(LoggingEvent.Severity.Trace
, string.Format(Constants._ModuleHostTotalEventsInStack
, _EventsInProgress.Count));
}
}
// Added try/finally block to ensure that events that throw an exception are still removed from the EventsInProgress
// list. A try block without the catch will bubble any exceptions thrown.
try
{
// Pass the event over to the ModuleCollection for handling. This keeps things more readable in this class.
if (_ModuleCollection != null)
{
_ModuleCollection.Handle(e);
}
}
catch(Exception ex)
{
// If an exception is thrown while handling an event, we attempt to log the exception and the event that caused it.
// If the current event is a LoggingEvent, we don't want to log the exception as this may cause a loop.
if (!isLoggingEvent)
{
Log(LoggingEvent.Severity.Error
, Constants._ModuleHostEventException
, e is ISensitiveEvent ? e.Name : e
, ex);
}
}
finally
{
if (!isLoggingEvent)
{
Log(LoggingEvent.Severity.Trace
, Constants._ModuleHostEventProcessed, string.Format(Constants._ModuleHostEventHandled, e is IUnhandledEvent ? "Unhandleable" : e.Handled)
, e is ISensitiveEvent ? e.Name : e);
}
// Once the event is completed we need to remove it from the EventsInProgress list.
lock (_EventsInProgress)
{
_EventsInProgress.Remove(id);
if (!isLoggingEvent)
{
Log(LoggingEvent.Severity.Trace
, string.Format(Constants._ModuleHostTotalEventsInStack
, _EventsInProgress.Count));
}
}
}
}
/// <summary>
/// This method works the same as <see cref="Handle(IEvent)"/>, and is used to handle an <see cref="IEvent"/> and return the same
/// <see cref="IEvent"/> back to the caller. This is useful when instantiating an <see cref="IEvent"/> for handling within its own
/// "if" closure and provides access to the instantiated <see cref="IEvent"/> through the outEvent parameter.
/// </summary>
public virtual bool TryHandle(IEvent inEvent, out IEvent outEvent)
{
Handle(inEvent);
outEvent = inEvent;
return inEvent.Handled;
}
/// <summary>
/// This method works the same as <see cref="Handle(IEvent)"/>, and is used to handle an <see cref="IEvent"/> and return the same
/// <see cref="IEvent"/> back to the caller. This is useful when instantiating an <see cref="IEvent"/> for handling within its own
/// "if" closure and provides access to the instantiated <see cref="IEvent"/> through the outEvent parameter.
/// </summary>
public virtual bool TryHandle<E>(E inEvent, out E outEvent) where E: IEvent
{
Handle(inEvent);
outEvent = inEvent;
return inEvent.Handled;
}
/// <summary>
/// <see cref="ModuleHost"/> implements <see cref="IEventHandler"/> and exposes its methods so that a <see cref="IModule"/>
/// instance can check to see if an <see cref="IEvent"/> instance can be handled and pass it to <see cref="ModuleHost.Handle(IEvent)"/>
/// for handling. It is recommended to always use <see cref="IModuleHost"/> to handle events rather than invoking
/// <see cref="Module.Handle(IEvent)"/> directly. Invoking <see cref="Module.Handle(IEvent)"/> will create a ghost event
/// that will be invisible to the <see cref="IModuleHost"/> and all other modules.
/// </summary>
public virtual async Task<IEvent> HandleAsync(IEvent e, CancellationToken cancellationToken)
{
return await Task.Run(() =>
{
if (e is ICancellable c && c.CancellationToken != cancellationToken)
{
c.SetCancelToken(cancellationToken);
}
Handle(e);
return e;
}, cancellationToken);
}
/// <summary>
/// Internal method for generating a unique event id.
/// </summary>
private string GenerateEventId(IEvent e)
{
return Guid.NewGuid().ToString("N");
}
/// <summary>
///
/// </summary>
public virtual void Log(LoggingEvent.Severity severity, params object[] arguments)
{
/*
* This overridable method creates a LoggingEvent, populates its properties and passes it to the Handle method for handling.
* If a module does not exist to handle an IEvent of type LoggingEvent logging will fail silently. If we were to attempt
* logging of a failed LoggingEvent we would create an infinite loop of logging fails... I hear StackOverflowException.
*/
if (arguments != null && arguments.Length > 0)
{
// We insert the application name at index 0 of the arguments array, and raise a LoggingEvent
// so that it can processed by any LoggingEvent event handlers.
var loggingEvent = new LoggingEvent
{
Input = new LoggingEventInput
{
Severity = severity,
Arguments = arguments.ToList()
}
};
loggingEvent.Input.Arguments.Insert(0, ApplicationName);
Handle(loggingEvent);
}
}
}
}