/
ServiceControlComponentRunner.cs
190 lines (162 loc) · 9.57 KB
/
ServiceControlComponentRunner.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
namespace ServiceControl.AcceptanceTests.TestSupport
{
using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using AcceptanceTesting;
using Hosting.Commands;
using Infrastructure.DomainEvents;
using Infrastructure.WebApi;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog;
using NServiceBus;
using NServiceBus.AcceptanceTesting;
using NServiceBus.AcceptanceTesting.Support;
using NServiceBus.Configuration.AdvancedExtensibility;
using Particular.ServiceControl;
using Particular.ServiceControl.Hosting;
using RavenDB.Shared;
using ServiceBus.Management.Infrastructure.Settings;
public class ServiceControlComponentRunner : ComponentRunner, IAcceptanceTestInfrastructureProvider
{
public ServiceControlComponentRunner(ITransportIntegration transportToUse, AcceptanceTestStorageConfiguration persistenceToUse, Action<Settings> setSettings, Action<EndpointConfiguration> customConfiguration, Action<IHostApplicationBuilder> hostBuilderCustomization)
{
this.transportToUse = transportToUse;
this.persistenceToUse = persistenceToUse;
this.customConfiguration = customConfiguration;
this.hostBuilderCustomization = hostBuilderCustomization;
this.setSettings = setSettings;
}
public override string Name { get; } = $"{nameof(ServiceControlComponentRunner)}";
public Settings Settings { get; private set; }
public HttpClient HttpClient { get; private set; }
public JsonSerializerOptions SerializerOptions => Infrastructure.WebApi.SerializerOptions.Default;
public Func<HttpMessageHandler> HttpMessageHandlerFactory { get; private set; }
public IDomainEvents DomainEvents { get; private set; }
public Task Initialize(RunDescriptor run) => InitializeServiceControl(run.ScenarioContext);
async Task InitializeServiceControl(ScenarioContext context)
{
var settings = new Settings(instanceName, transportToUse.TypeName, persistenceToUse.PersistenceType, forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(10))
{
AllowMessageEditing = true,
ForwardErrorMessages = false,
TransportConnectionString = transportToUse.ConnectionString,
ProcessRetryBatchesFrequency = TimeSpan.FromSeconds(2),
TimeToRestartErrorIngestionAfterFailure = TimeSpan.FromSeconds(2),
MaximumConcurrencyLevel = 2,
HttpDefaultConnectionLimit = int.MaxValue,
DisableHealthChecks = true,
ExposeApi = true,
MessageFilter = messageContext =>
{
var headers = messageContext.Headers;
var id = messageContext.NativeMessageId;
var log = NServiceBus.Logging.LogManager.GetLogger<ServiceControlComponentRunner>();
headers.TryGetValue(Headers.MessageId, out var originalMessageId);
log.Debug($"OnMessage for message '{id}'({originalMessageId ?? string.Empty}).");
//Do not filter out CC, SA and HB messages as they can't be stamped
if (headers.TryGetValue(Headers.EnclosedMessageTypes, out var messageTypes)
&& (messageTypes.StartsWith("ServiceControl.Contracts") || messageTypes.StartsWith("ServiceControl.EndpointPlugin")))
{
return false;
}
//Do not filter out subscribe messages as they can't be stamped
if (headers.TryGetValue(Headers.MessageIntent, out var intent)
&& intent == MessageIntent.Subscribe.ToString())
{
return false;
}
var currentSession = context.TestRunId.ToString();
if (!headers.TryGetValue("SC.SessionID", out var session) || session != currentSession)
{
log.Debug($"Discarding message '{id}'({originalMessageId ?? string.Empty}) because it's session id is '{session}' instead of '{currentSession}'.");
return true;
}
return false;
},
};
await persistenceToUse.CustomizeSettings(settings);
setSettings(settings);
Settings = settings;
using (new DiagnosticTimer($"Creating infrastructure for {instanceName}"))
{
var setupCommand = new SetupCommand();
await setupCommand.Execute(new HostArguments(Array.Empty<string>()), settings);
}
var configuration = new EndpointConfiguration(instanceName);
configuration.GetSettings().Set("SC.ScenarioContext", context);
configuration.GetSettings().Set(context);
configuration.RegisterComponents(r =>
{
r.AddSingleton(context.GetType(), context);
r.AddSingleton(typeof(ScenarioContext), context);
});
configuration.Pipeline.Register<TraceIncomingBehavior.Registration>();
configuration.Pipeline.Register<TraceOutgoingBehavior.Registration>();
configuration.Pipeline.Register(new StampDispatchBehavior(context), "Stamps outgoing messages with session ID");
configuration.Pipeline.Register(new DiscardMessagesBehavior(context), "Discards messages based on session ID");
var assemblyScanner = configuration.AssemblyScanner();
assemblyScanner.ExcludeAssemblies(Path.GetFileName(typeof(ServiceControlComponentRunner).Assembly.Location));
customConfiguration(configuration);
using (new DiagnosticTimer($"Starting ServiceControl {instanceName}"))
{
var logPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(logPath);
var loggingSettings = new LoggingSettings(settings.ServiceName, defaultLevel: LogLevel.Debug, logPath: logPath);
var hostBuilder = WebApplication.CreateBuilder(new WebApplicationOptions
{
// Force the DI container to run the dependency resolution check to verify all dependencies can be resolved
EnvironmentName = Environments.Development
});
hostBuilder.AddServiceControl(settings, configuration, loggingSettings);
// Do not register additional test controllers or hosted services here. Instead, in the test that needs them, use (for example):
// CustomizeHostBuilder = builder => builder.ConfigureServices((hostContext, services) => services.AddHostedService<SetupNotificationSettings>());
hostBuilder.Logging.AddScenarioContextLogging();
// TODO: the following four lines could go into a AddServiceControlTesting() extension
hostBuilder.WebHost.UseTestServer(options => options.BaseAddress = new Uri(settings.RootUrl));
hostBuilder.Services.AddSingleton<IHostLifetime, TestServerHostLifetime>();
// This facilitates receiving the test server anywhere where DI is available
hostBuilder.Services.AddSingleton(provider => (TestServer)provider.GetRequiredService<IServer>());
// By default ASP.NET Core uses entry point assembly to discover controllers from. When running
// inside a test runner the runner exe becomes the entry point which obviously has no controllers in it ;)
// so we are explicitly registering all necessary application parts.
var addControllers = hostBuilder.Services.AddControllers();
addControllers.AddApplicationPart(typeof(WebApiHostBuilderExtensions).Assembly);
addControllers.AddApplicationPart(typeof(AcceptanceTest).Assembly);
hostBuilder.Services.OverrideHttpClientDefaults(settings);
hostBuilderCustomization(hostBuilder);
host = hostBuilder.Build();
host.UseServiceControl();
await host.StartAsync();
DomainEvents = host.Services.GetRequiredService<IDomainEvents>();
// Bring this back and look into the base address of the client
HttpClient = host.GetTestServer().CreateClient();
HttpMessageHandlerFactory = () => host.GetTestServer().CreateHandler();
}
}
public override async Task Stop(CancellationToken cancellationToken = default)
{
using (new DiagnosticTimer($"Test TearDown for {instanceName}"))
{
await host.StopAsync(cancellationToken);
HttpClient.Dispose();
await host.DisposeAsync();
await persistenceToUse.Cleanup();
}
}
WebApplication host;
readonly ITransportIntegration transportToUse;
readonly AcceptanceTestStorageConfiguration persistenceToUse;
readonly Action<Settings> setSettings;
readonly Action<EndpointConfiguration> customConfiguration;
readonly Action<IHostApplicationBuilder> hostBuilderCustomization;
readonly string instanceName = Settings.DEFAULT_SERVICE_NAME;
}
}