forked from dotnet/aspire
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTestDistributedApplicationBuilder.cs
More file actions
218 lines (177 loc) · 7.92 KB
/
TestDistributedApplicationBuilder.cs
File metadata and controls
218 lines (177 loc) · 7.92 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Aspire.Components.Common.Tests;
using Aspire.Hosting.Dashboard;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Aspire.Hosting.Utils;
/// <summary>
/// DistributedApplication.CreateBuilder() creates a builder that includes configuration to read from appsettings.json.
/// The builder has a FileSystemWatcher, which can't be cleaned up unless a DistributedApplication is built and disposed.
/// This class wraps the builder and provides a way to automatically dispose it to prevent test failures from excessive
/// FileSystemWatcher instances from many tests.
/// </summary>
public sealed class TestDistributedApplicationBuilder : IDistributedApplicationBuilder, IDisposable
{
private readonly DistributedApplicationBuilder _innerBuilder;
private bool _disposedValue;
private DistributedApplication? _app;
public static TestDistributedApplicationBuilder Create(DistributedApplicationOperation operation)
{
var args = operation switch
{
DistributedApplicationOperation.Run => (string[])[],
DistributedApplicationOperation.Publish => ["Publishing:Publisher=manifest"],
_ => throw new ArgumentOutOfRangeException(nameof(operation))
};
return Create(args);
}
public static TestDistributedApplicationBuilder Create(params string[] args)
{
return new TestDistributedApplicationBuilder(options => options.Args = args);
}
public static TestDistributedApplicationBuilder Create(Action<DistributedApplicationOptions>? configureOptions)
{
return new TestDistributedApplicationBuilder(configureOptions);
}
public static TestDistributedApplicationBuilder CreateWithTestContainerRegistry() =>
Create(o => o.ContainerRegistryOverride = TestConstants.AspireTestContainerRegistry);
private TestDistributedApplicationBuilder(Action<DistributedApplicationOptions>? configureOptions)
{
var appAssembly = typeof(TestDistributedApplicationBuilder).Assembly;
var assemblyName = appAssembly.FullName;
_innerBuilder = BuilderInterceptor.CreateBuilder(Configure);
_innerBuilder.Services.Configure<DashboardOptions>(o =>
{
// Make sure we have a dashboard URL and OTLP endpoint URL (but don't overwrite them if they're already set)
o.DashboardUrl ??= "http://localhost:8080";
o.OtlpGrpcEndpointUrl ??= "http://localhost:4317";
});
_innerBuilder.Services.AddHttpClient();
_innerBuilder.Services.ConfigureHttpClientDefaults(http => http.AddStandardResilienceHandler());
void Configure(DistributedApplicationOptions applicationOptions, HostApplicationBuilderSettings hostBuilderOptions)
{
hostBuilderOptions.EnvironmentName = Environments.Development;
hostBuilderOptions.ApplicationName = appAssembly.GetName().Name;
applicationOptions.AssemblyName = assemblyName;
applicationOptions.DisableDashboard = true;
var cfg = hostBuilderOptions.Configuration ??= new();
cfg.AddInMemoryCollection(new Dictionary<string, string?>
{
["DcpPublisher:RandomizePorts"] = "true",
["DcpPublisher:DeleteResourcesOnShutdown"] = "true",
["DcpPublisher:ResourceNameSuffix"] = $"{Random.Shared.Next():x}",
});
configureOptions?.Invoke(applicationOptions);
}
}
public ConfigurationManager Configuration => _innerBuilder.Configuration;
public string AppHostDirectory => _innerBuilder.AppHostDirectory;
public Assembly? AppHostAssembly => _innerBuilder.AppHostAssembly;
public IHostEnvironment Environment => _innerBuilder.Environment;
public IServiceCollection Services => _innerBuilder.Services;
public DistributedApplicationExecutionContext ExecutionContext => _innerBuilder.ExecutionContext;
public IResourceCollection Resources => _innerBuilder.Resources;
public IResourceBuilder<T> AddResource<T>(T resource) where T : IResource => _innerBuilder.AddResource(resource);
[MemberNotNull(nameof(_app))]
public DistributedApplication Build() => _app = _innerBuilder.Build();
public Task<DistributedApplication> BuildAsync(CancellationToken cancellationToken = default) => Task.FromResult(Build());
public IResourceBuilder<T> CreateResourceBuilder<T>(T resource) where T : IResource
{
return _innerBuilder.CreateResourceBuilder(resource);
}
public void Dispose()
{
if (!_disposedValue)
{
_disposedValue = true;
if (_app is null)
{
try
{
Build();
}
catch
{
}
}
_app?.Dispose();
}
}
private sealed class BuilderInterceptor : IObserver<DiagnosticListener>
{
private static readonly ThreadLocal<BuilderInterceptor?> s_currentListener = new();
private readonly ApplicationBuilderDiagnosticListener _applicationBuilderListener;
private readonly Action<DistributedApplicationOptions, HostApplicationBuilderSettings>? _onConstructing;
private BuilderInterceptor(Action<DistributedApplicationOptions, HostApplicationBuilderSettings>? onConstructing)
{
_onConstructing = onConstructing;
_applicationBuilderListener = new(this);
}
public static DistributedApplicationBuilder CreateBuilder(Action<DistributedApplicationOptions, HostApplicationBuilderSettings> onConstructing)
{
var interceptor = new BuilderInterceptor(onConstructing);
var original = s_currentListener.Value;
s_currentListener.Value = interceptor;
try
{
using var subscription = DiagnosticListener.AllListeners.Subscribe(interceptor);
return new DistributedApplicationBuilder([]);
}
finally
{
s_currentListener.Value = original;
}
}
public void OnCompleted()
{
}
public void OnError(Exception error)
{
}
public void OnNext(DiagnosticListener value)
{
if (s_currentListener.Value != this)
{
// Ignore events that aren't for this listener
return;
}
if (value.Name == "Aspire.Hosting")
{
_applicationBuilderListener.Subscribe(value);
}
}
private sealed class ApplicationBuilderDiagnosticListener(BuilderInterceptor owner) : IObserver<KeyValuePair<string, object?>>
{
private IDisposable? _disposable;
public void Subscribe(DiagnosticListener listener)
{
_disposable = listener.Subscribe(this);
}
public void OnCompleted()
{
_disposable?.Dispose();
}
public void OnError(Exception error)
{
}
public void OnNext(KeyValuePair<string, object?> value)
{
if (s_currentListener.Value != owner)
{
// Ignore events that aren't for this listener
return;
}
if (value.Key == "DistributedApplicationBuilderConstructing")
{
var (options, innerBuilderOptions) = ((DistributedApplicationOptions, HostApplicationBuilderSettings))value.Value!;
owner._onConstructing?.Invoke(options, innerBuilderOptions);
}
}
}
}
}