/
Sagas.cs
463 lines (373 loc) · 17.6 KB
/
Sagas.cs
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
namespace NServiceBus.Features
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Config;
using Logging;
using NServiceBus.Sagas;
using NServiceBus.Sagas.Finders;
using Saga;
public class Sagas : Feature
{
public override void Initialize()
{
var sagasFound = FindAndConfigureSagasIn(Configure.TypesToScan);
if (sagasFound)
{
InfrastructureServices.Enable<ISagaPersister>();
Logger.InfoFormat("Sagas found in scanned types, saga persister enabled");
}
else
{
Logger.InfoFormat("The saga feature was enabled but no saga implementations could be found. No need to enable the configured saga persister");
}
}
/// <summary>
/// Scans for types relevant to the saga infrastructure.
/// These include implementers of <see cref="ISaga" /> and <see cref="IFindSagas{T}" />.
/// </summary>
public bool FindAndConfigureSagasIn(IEnumerable<Type> types)
{
var sagasWereFound = false;
foreach (var t in types)
{
if (IsSagaType(t))
{
Configure.Component(t, DependencyLifecycle.InstancePerCall);
ConfigureSaga(t);
sagasWereFound = true;
continue;
}
if (IsFinderType(t))
{
Configure.Component(t, DependencyLifecycle.InstancePerCall);
ConfigureFinder(t);
continue;
}
if (IsSagaNotFoundHandler(t))
{
Configure.Component(t, DependencyLifecycle.InstancePerCall);
continue;
}
}
CreateAdditionalFindersAsNecessary();
return sagasWereFound;
}
internal static void ConfigureHowToFindSagaWithMessage(Type sagaType, PropertyInfo sagaProp, Type messageType, PropertyInfo messageProp)
{
IDictionary<Type, KeyValuePair<PropertyInfo, PropertyInfo>> messageToProperties;
SagaEntityToMessageToPropertyLookup.TryGetValue(sagaType, out messageToProperties);
if (messageToProperties == null)
{
messageToProperties = new Dictionary<Type, KeyValuePair<PropertyInfo, PropertyInfo>>();
SagaEntityToMessageToPropertyLookup[sagaType] = messageToProperties;
}
messageToProperties[messageType] = new KeyValuePair<PropertyInfo, PropertyInfo>(sagaProp, messageProp);
}
public static readonly IDictionary<Type, IDictionary<Type, KeyValuePair<PropertyInfo, PropertyInfo>>> SagaEntityToMessageToPropertyLookup = new Dictionary<Type, IDictionary<Type, KeyValuePair<PropertyInfo, PropertyInfo>>>();
void CreateAdditionalFindersAsNecessary()
{
foreach (var sagaEntityType in SagaEntityToMessageToPropertyLookup.Keys)
foreach (var messageType in SagaEntityToMessageToPropertyLookup[sagaEntityType].Keys)
{
var pair = SagaEntityToMessageToPropertyLookup[sagaEntityType][messageType];
CreatePropertyFinder(sagaEntityType, messageType, pair.Key, pair.Value);
}
foreach (var sagaType in SagaTypeToSagaEntityTypeLookup.Keys)
{
var sagaEntityType = SagaTypeToSagaEntityTypeLookup[sagaType];
var sagaHeaderIdFinder = typeof(HeaderSagaIdFinder<>).MakeGenericType(sagaEntityType);
Configure.Component(sagaHeaderIdFinder, DependencyLifecycle.InstancePerCall);
ConfigureFinder(sagaHeaderIdFinder);
}
}
private void CreatePropertyFinder(Type sagaEntityType, Type messageType, PropertyInfo sagaProperty, PropertyInfo messageProperty)
{
var finderType = typeof(PropertySagaFinder<,>).MakeGenericType(sagaEntityType, messageType);
Configure.Component(finderType, DependencyLifecycle.InstancePerCall)
.ConfigureProperty("SagaProperty", sagaProperty)
.ConfigureProperty("MessageProperty", messageProperty);
ConfigureFinder(finderType);
}
/// <summary>
/// True if the given message are configure to start the saga
/// </summary>
public static bool ShouldMessageStartSaga(Type sagaType, Type messageType)
{
List<Type> messageTypes;
SagaTypeToMessageTypesRequiringSagaStartLookup.TryGetValue(sagaType, out messageTypes);
if (messageTypes == null)
return false;
if (messageTypes.Contains(messageType))
return true;
return messageTypes.Any(msgTypeHandleBySaga => msgTypeHandleBySaga.IsAssignableFrom(messageType));
}
/// <summary>
/// Gets the saga type to instantiate and invoke if an existing saga couldn't be found by
/// the given finder using the given message.
/// </summary>
[ObsoleteEx(RemoveInVersion = "5.0", TreatAsErrorFromVersion = "4.4")]
public static Type GetSagaTypeToStartIfMessageNotFoundByFinder(object message, IFinder finder)
{
Type sagaEntityType;
FinderTypeToSagaEntityTypeLookup.TryGetValue(finder.GetType(), out sagaEntityType);
if (sagaEntityType == null)
return null;
Type sagaType;
SagaEntityTypeToSagaTypeLookup.TryGetValue(sagaEntityType, out sagaType);
if (sagaType == null)
return null;
List<Type> messageTypes;
SagaTypeToMessageTypesRequiringSagaStartLookup.TryGetValue(sagaType, out messageTypes);
if (messageTypes == null)
return null;
if (messageTypes.Contains(message.GetType()))
return sagaType;
foreach (var msgTypeHandleBySaga in messageTypes)
if (msgTypeHandleBySaga.IsInstanceOfType(message))
return sagaType;
return null;
}
/// <summary>
/// Returns the saga type configured for the given entity type.
/// </summary>
public static Type GetSagaTypeForSagaEntityType(Type sagaEntityType)
{
Type result;
SagaEntityTypeToSagaTypeLookup.TryGetValue(sagaEntityType, out result);
return result;
}
/// <summary>
/// Returns the entity type configured for the given saga type.
/// </summary>
public static Type GetSagaEntityTypeForSagaType(Type sagaType)
{
Type result;
SagaTypeToSagaEntityTypeLookup.TryGetValue(sagaType, out result);
return result;
}
/// <summary>
/// Gets a reference to the generic "FindBy" method of the given finder
/// for the given message type using a hashtable lookup rather than reflection.
/// </summary>
public static MethodInfo GetFindByMethodForFinder(IFinder finder, object message)
{
MethodInfo result = null;
IDictionary<Type, MethodInfo> methods;
FinderTypeToMessageToMethodInfoLookup.TryGetValue(finder.GetType(), out methods);
if (methods != null)
{
methods.TryGetValue(message.GetType(), out result);
if (result == null)
foreach (var messageType in methods.Keys)
if (messageType.IsInstanceOfType(message))
result = methods[messageType];
}
return result;
}
/// <summary>
/// Returns a list of finder object capable of using the given message.
/// </summary>
[ObsoleteEx(Replacement = "GetFindersForMessageAndEntity", TreatAsErrorFromVersion = "4.3")]
public static IEnumerable<Type> GetFindersFor(object m)
{
foreach (var finderType in FinderTypeToMessageToMethodInfoLookup.Keys)
{
var messageToMethodInfo = FinderTypeToMessageToMethodInfoLookup[finderType];
if (messageToMethodInfo.ContainsKey(m.GetType()))
{
yield return finderType;
continue;
}
foreach (var messageType in messageToMethodInfo.Keys)
if (messageType.IsInstanceOfType(m))
yield return finderType;
}
}
/// <summary>
/// Returns a list of finder object capable of using the given message.
/// </summary>
public static IEnumerable<Type> GetFindersForMessageAndEntity(Type messageType, Type entityType)
{
var findersWithExactMatch = new List<Type>();
var findersMatchingBaseTypes = new List<Type>();
foreach (var finderType in FinderTypeToMessageToMethodInfoLookup.Keys)
{
var messageToMethodInfo = FinderTypeToMessageToMethodInfoLookup[finderType];
MethodInfo methodInfo;
if (messageToMethodInfo.TryGetValue(messageType, out methodInfo) && methodInfo.ReturnType == entityType)
{
findersWithExactMatch.Add(finderType);
}
else
{
foreach (var otherMessage in messageToMethodInfo.Keys)
{
if (otherMessage.IsAssignableFrom(messageType) && messageToMethodInfo[otherMessage].ReturnType == entityType)
{
findersMatchingBaseTypes.Add(finderType);
}
}
}
}
return findersWithExactMatch.Concat(findersMatchingBaseTypes);
}
/// <summary>
/// Returns the list of saga types configured.
/// </summary>
public static IEnumerable<Type> GetSagaDataTypes()
{
return SagaTypeToSagaEntityTypeLookup.Values;
}
public static bool IsSagaType(Type t)
{
return IsCompatible(t, typeof(ISaga));
}
static bool IsFinderType(Type t)
{
return IsCompatible(t, typeof(IFinder));
}
static bool IsSagaNotFoundHandler(Type t)
{
return IsCompatible(t, typeof(IHandleSagaNotFound));
}
static bool IsCompatible(Type t, Type source)
{
return source.IsAssignableFrom(t) && t != source && !t.IsAbstract && !t.IsInterface && !t.IsGenericType;
}
public static void ConfigureSaga(Type t)
{
foreach (var messageType in GetMessageTypesHandledBySaga(t))
MapMessageTypeToSagaType(messageType, t);
foreach (var messageType in GetMessageTypesThatRequireStartingTheSaga(t))
MessageTypeRequiresStartingSaga(messageType, t);
var prop = t.GetProperty("Data");
MapSagaTypeToSagaEntityType(t, prop.PropertyType);
if (!typeof(IConfigurable).IsAssignableFrom(t))
return;
var defaultConstructor = t.GetConstructor(Type.EmptyTypes);
if (defaultConstructor == null)
throw new InvalidOperationException("Sagas which implement IConfigurable, like those which inherit from Saga<T>, must have a default constructor.");
var saga = Activator.CreateInstance(t) as ISaga;
var p = t.GetProperty("SagaMessageFindingConfiguration", typeof(IConfigureHowToFindSagaWithMessage));
if (p != null)
p.SetValue(saga, SagaMessageFindingConfiguration, null);
if (saga is IConfigurable)
(saga as IConfigurable).Configure();
}
public static void ConfigureFinder(Type t)
{
foreach (var interfaceType in t.GetInterfaces())
{
var args = interfaceType.GetGenericArguments();
if (args.Length != 2)
continue;
Type sagaEntityType = null;
Type messageType = null;
foreach (var type in args)
{
if (typeof(IContainSagaData).IsAssignableFrom(type))
sagaEntityType = type;
if (MessageConventionExtensions.IsMessageType(type) || type == typeof(object))
messageType = type;
}
if (sagaEntityType == null || messageType == null)
continue;
var finderType = typeof(IFindSagas<>.Using<>).MakeGenericType(sagaEntityType, messageType);
if (!finderType.IsAssignableFrom(t))
continue;
FinderTypeToSagaEntityTypeLookup[t] = sagaEntityType;
var method = t.GetMethod("FindBy", new[] { messageType });
IDictionary<Type, MethodInfo> methods;
FinderTypeToMessageToMethodInfoLookup.TryGetValue(t, out methods);
if (methods == null)
{
methods = new Dictionary<Type, MethodInfo>();
FinderTypeToMessageToMethodInfoLookup[t] = methods;
}
methods[messageType] = method;
}
}
internal static IEnumerable<Type> GetMessageTypesHandledBySaga(Type sagaType)
{
return GetMessagesCorrespondingToFilterOnSaga(sagaType, typeof(IHandleMessages<>));
}
internal static IEnumerable<Type> GetMessageTypesThatRequireStartingTheSaga(Type sagaType)
{
return GetMessagesCorrespondingToFilterOnSaga(sagaType, typeof(IAmStartedByMessages<>));
}
static IEnumerable<Type> GetMessagesCorrespondingToFilterOnSaga(Type sagaType, Type filter)
{
foreach (var interfaceType in sagaType.GetInterfaces())
{
foreach (var argument in interfaceType.GetGenericArguments())
{
var genericType = filter.MakeGenericType(argument);
var isOfFilterType = genericType == interfaceType;
if (!isOfFilterType)
{
continue;
}
if (MessageConventionExtensions.IsMessageType(argument))
{
yield return argument;
continue;
}
var message = string.Format("The saga '{0}' implements '{1}' but the message type '{2}' is not classified as a message. You should either use 'Unobtrusive Mode Messages' or the message should implement either 'IMessage', 'IEvent' or 'ICommand'.", sagaType.FullName, genericType.Name, argument.FullName);
throw new Exception(message);
}
}
}
static void MapMessageTypeToSagaType(Type messageType, Type sagaType)
{
List<Type> sagas;
MessageTypeToSagaTypesLookup.TryGetValue(messageType, out sagas);
if (sagas == null)
{
sagas = new List<Type>(1);
MessageTypeToSagaTypesLookup[messageType] = sagas;
}
if (!sagas.Contains(sagaType))
sagas.Add(sagaType);
}
static void MapSagaTypeToSagaEntityType(Type sagaType, Type sagaEntityType)
{
SagaTypeToSagaEntityTypeLookup[sagaType] = sagaEntityType;
SagaEntityTypeToSagaTypeLookup[sagaEntityType] = sagaType;
}
static void MessageTypeRequiresStartingSaga(Type messageType, Type sagaType)
{
List<Type> messages;
SagaTypeToMessageTypesRequiringSagaStartLookup.TryGetValue(sagaType, out messages);
if (messages == null)
{
messages = new List<Type>(1);
SagaTypeToMessageTypesRequiringSagaStartLookup[sagaType] = messages;
}
if (!messages.Contains(messageType))
messages.Add(messageType);
}
readonly static IDictionary<Type, List<Type>> MessageTypeToSagaTypesLookup = new Dictionary<Type, List<Type>>();
static readonly IDictionary<Type, Type> SagaEntityTypeToSagaTypeLookup = new Dictionary<Type, Type>();
static readonly IDictionary<Type, Type> SagaTypeToSagaEntityTypeLookup = new Dictionary<Type, Type>();
static readonly IDictionary<Type, Type> FinderTypeToSagaEntityTypeLookup = new Dictionary<Type, Type>();
static readonly IDictionary<Type, IDictionary<Type, MethodInfo>> FinderTypeToMessageToMethodInfoLookup = new Dictionary<Type, IDictionary<Type, MethodInfo>>();
static readonly IDictionary<Type, List<Type>> SagaTypeToMessageTypesRequiringSagaStartLookup = new Dictionary<Type, List<Type>>();
static readonly IConfigureHowToFindSagaWithMessage SagaMessageFindingConfiguration = new ConfigureHowToFindSagaWithMessageDispatcher();
static readonly ILog Logger = LogManager.GetLogger(typeof(Sagas));
/// <summary>
/// Until we get rid of those statics
/// </summary>
public static void Clear()
{
MessageTypeToSagaTypesLookup.Clear();
SagaEntityTypeToSagaTypeLookup.Clear();
SagaTypeToSagaEntityTypeLookup.Clear();
FinderTypeToSagaEntityTypeLookup.Clear();
FinderTypeToMessageToMethodInfoLookup.Clear();
SagaTypeToMessageTypesRequiringSagaStartLookup.Clear();
}
}
}