-
Notifications
You must be signed in to change notification settings - Fork 46
/
WebApplicationBuilderExtensions.cs
184 lines (149 loc) · 7.1 KB
/
WebApplicationBuilderExtensions.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
namespace ServiceControl.Monitoring;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Infrastructure;
using Infrastructure.Extensions;
using Infrastructure.WebApi;
using Licensing;
using Messaging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NServiceBus;
using NServiceBus.Configuration.AdvancedExtensibility;
using NServiceBus.Features;
using NServiceBus.Transport;
using QueueLength;
using Timings;
using Transports;
public static class WebApplicationBuilderExtensions
{
public static void AddServiceControlMonitoring(this WebApplicationBuilder hostBuilder,
Func<ICriticalErrorContext, CancellationToken, Task> onCriticalError, Settings settings,
EndpointConfiguration endpointConfiguration)
{
var transportCustomization = settings.LoadTransportCustomization();
var buildQueueLengthProvider = QueueLengthProviderBuilder(settings.ConnectionString, transportCustomization);
hostBuilder.Services.AddWindowsService();
hostBuilder.Logging.ClearProviders();
//HINT: configuration used by NLog comes from MonitorLog.cs
hostBuilder.Logging.AddNLog();
hostBuilder.Logging.SetMinimumLevel(ToHostLogLevel(settings.LogLevel));
var services = hostBuilder.Services;
services.AddSingleton(settings);
services.AddSingleton<LicenseCheckFeatureStartup>();
services.AddSingleton<EndpointRegistry>();
services.AddSingleton<MessageTypeRegistry>();
services.AddSingleton<EndpointInstanceActivityTracker>();
services.AddSingleton(sp => buildQueueLengthProvider(sp.GetRequiredService<QueueLengthStore>()));
services.AddSingleton<LegacyQueueLengthReportHandler.LegacyQueueLengthEndpoints>();
services.RegisterAsSelfAndImplementedInterfaces<RetriesStore>();
services.RegisterAsSelfAndImplementedInterfaces<CriticalTimeStore>();
services.RegisterAsSelfAndImplementedInterfaces<ProcessingTimeStore>();
services.RegisterAsSelfAndImplementedInterfaces<QueueLengthStore>();
services.AddHttpLogging(options =>
{
// TODO Do we need to expose the host?
// we could also include the time it took to process the request
options.LoggingFields = HttpLoggingFields.RequestPath | HttpLoggingFields.RequestMethod | HttpLoggingFields.ResponseStatusCode;
});
// Core registers the message dispatcher to be resolved from the transport seam. The dispatcher
// is only available though after the NServiceBus hosted service has started. Any hosted service
// or component injected into a hosted service can only depend on this lazy instead of the dispatcher
// directly and to make things more complex of course the order of registration still matters ;)
services.AddSingleton(provider => new Lazy<IMessageDispatcher>(provider.GetRequiredService<IMessageDispatcher>));
ConfigureEndpoint(endpointConfiguration, onCriticalError, transportCustomization, settings);
hostBuilder.UseNServiceBus(endpointConfiguration);
// TODO Verify if that we need to check the expose API flag
// We also don't do this in the primary instance
hostBuilder.WebHost.UseUrls(settings.RootUrl);
var controllers = hostBuilder.Services.AddControllers(options =>
{
options.Filters.Add<XParticularVersionHttpHandler>();
options.Filters.Add<CachingHttpHandler>();
});
controllers.AddJsonOptions(options => options.JsonSerializerOptions.CustomizeDefaults());
}
internal static void ConfigureEndpoint(EndpointConfiguration config, Func<ICriticalErrorContext, CancellationToken, Task> onCriticalError, ITransportCustomization transportCustomization, Settings settings)
{
if (!string.IsNullOrWhiteSpace(settings.LicenseFileText))
{
config.License(settings.LicenseFileText);
}
var transportSettings = new TransportSettings
{
RunCustomChecks = false,
ConnectionString = settings.ConnectionString,
EndpointName = settings.EndpointName,
MaxConcurrency = settings.MaximumConcurrencyLevel
};
transportCustomization.CustomizeMonitoringEndpoint(config, transportSettings);
if (settings.EnableInstallers)
{
config.EnableInstallers(settings.Username);
}
config.DefineCriticalErrorAction(onCriticalError);
config.GetSettings().Set(settings);
config.SetDiagnosticsPath(settings.LogPath);
config.LimitMessageProcessingConcurrencyTo(settings.MaximumConcurrencyLevel);
config.UseSerialization<NewtonsoftJsonSerializer>();
config.UsePersistence<NonDurablePersistence>();
var recoverability = config.Recoverability();
recoverability.Immediate(c => c.NumberOfRetries(3));
recoverability.Delayed(c => c.NumberOfRetries(0));
config.SendFailedMessagesTo(settings.ErrorQueue);
config.DisableFeature<AutoSubscribe>();
config.AddDeserializer<TaggedLongValueWriterOccurrenceSerializerDefinition>();
config.Pipeline.Register(typeof(MessagePoolReleasingBehavior), "Releases pooled message.");
config.EnableFeature<QueueLength.QueueLength>();
config.EnableFeature<LicenseCheckFeature>();
}
static Func<QueueLengthStore, IProvideQueueLength> QueueLengthProviderBuilder(string connectionString,
ITransportCustomization transportCustomization) =>
qls =>
{
var queueLengthProvider = transportCustomization.CreateQueueLengthProvider();
Action<QueueLengthEntry[], EndpointToQueueMapping> store = (es, q) =>
qls.Store(es.Select(e => ToEntry(e)).ToArray(), ToQueueId(q));
queueLengthProvider.Initialize(connectionString, store);
return queueLengthProvider;
};
static EndpointInputQueue ToQueueId(EndpointToQueueMapping endpointInputQueueDto)
=> new EndpointInputQueue(endpointInputQueueDto.EndpointName, endpointInputQueueDto.InputQueue);
static RawMessage.Entry ToEntry(QueueLengthEntry entryDto) =>
new RawMessage.Entry { DateTicks = entryDto.DateTicks, Value = entryDto.Value };
public static LogLevel ToHostLogLevel(NLog.LogLevel logLevel)
{
if (logLevel == NLog.LogLevel.Debug)
{
return LogLevel.Debug;
}
if (logLevel == NLog.LogLevel.Error)
{
return LogLevel.Error;
}
if (logLevel == NLog.LogLevel.Fatal)
{
return LogLevel.Critical;
}
if (logLevel == NLog.LogLevel.Warn)
{
return LogLevel.Warning;
}
if (logLevel == NLog.LogLevel.Info)
{
return LogLevel.Information;
}
if (logLevel == NLog.LogLevel.Trace)
{
return LogLevel.Trace;
}
return LogLevel.None;
}
}