-
Notifications
You must be signed in to change notification settings - Fork 462
/
ProjectResourceBuilderExtensions.cs
436 lines (392 loc) · 21.4 KB
/
ProjectResourceBuilderExtensions.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Dashboard;
using Aspire.Hosting.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace Aspire.Hosting;
/// <summary>
/// Provides extension methods for <see cref="IDistributedApplicationBuilder"/> to add and configure project resources.
/// </summary>
public static class ProjectResourceBuilderExtensions
{
private const string AspNetCoreForwaredHeadersEnabledVariableName = "ASPNETCORE_FORWARDEDHEADERS_ENABLED";
/// <summary>
/// Adds a .NET project to the application model.
/// </summary>
/// <typeparam name="TProject">A type that represents the project reference.</typeparam>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <param name="name">The name of the resource. This name will be used for service discovery when referenced in a dependency.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// <para>
/// This overload of the <see cref="AddProject{TProject}(IDistributedApplicationBuilder, string)"/> method takes
/// a <typeparamref name="TProject"/> type parameter. The <typeparamref name="TProject"/> type parameter is constrained
/// to types that implement the <see cref="IProjectMetadata"/> interface.
/// </para>
/// <para>
/// Classes that implement the <see cref="IProjectMetadata"/> interface are generated when a .NET project is added as a reference
/// to the app host project. The generated class contains a property that returns the path to the referenced project file. Using this path
/// .NET Aspire parses the <c>launchSettings.json</c> file to determine which launch profile to use when running the project, and
/// what endpoint configuration to automatically generate.
/// </para>
/// <para>
/// The name of the automatically generated project metadata type is a normalized version of the project name. Periods, dashes, and
/// spaces in project names are converted to underscores. This normalization may lead to naming conflicts. If a conflict occurs the <c><ProjectReference /></c>
/// that references the project can have a <c>AspireProjectMetadataTypeName="..."</c> attribute added to override the name.
/// </para>
/// </remarks>
/// <example>
/// Example of adding a project to the application model.
/// <code lang="C#">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddProject<Projects.InventoryService>("inventoryservice");
///
/// builder.Build().Run();
/// </code>
/// </example>
public static IResourceBuilder<ProjectResource> AddProject<TProject>(this IDistributedApplicationBuilder builder, string name) where TProject : IProjectMetadata, new()
{
var project = new ProjectResource(name);
return builder.AddResource(project)
.WithAnnotation(new TProject())
.WithProjectDefaults(excludeLaunchProfile: false, launchProfileName: null);
}
/// <summary>
/// Adds a .NET project to the application model.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <param name="name">The name of the resource. This name will be used for service discovery when referenced in a dependency.</param>
/// <param name="projectPath">The path to the project file.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// <para>
/// This overload of the <see cref="AddProject(IDistributedApplicationBuilder, string, string)"/> method adds a project to the application
/// model using an path to the project file. This allows for projects to be referenced that may not be part of the same solution. If the project
/// path is not an absolute path then it will be computed relative to the app host directory.
/// </para>
/// </remarks>
/// <example>
/// Add a project to the app model via a project path.
/// <code lang="C#">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddProject("inventoryservice", @"..\InventoryService\InventoryService.csproj");
///
/// builder.Build().Run();
/// </code>
/// </example>
public static IResourceBuilder<ProjectResource> AddProject(this IDistributedApplicationBuilder builder, string name, string projectPath)
{
var project = new ProjectResource(name);
projectPath = PathNormalizer.NormalizePathForCurrentPlatform(Path.Combine(builder.AppHostDirectory, projectPath));
return builder.AddResource(project)
.WithAnnotation(new ProjectMetadata(projectPath))
.WithProjectDefaults(excludeLaunchProfile: false, launchProfileName: null);
}
/// <summary>
/// Adds a .NET project to the application model. By default, this will exist in a Projects namespace. e.g. Projects.MyProject.
/// If the project is not in a Projects namespace, make sure a project reference is added from the AppHost project to the target project.
/// </summary>
/// <typeparam name="TProject">A type that represents the project reference.</typeparam>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <param name="name">The name of the resource. This name will be used for service discovery when referenced in a dependency.</param>
/// <param name="launchProfileName">The launch profile to use. If <c>null</c> then no launch profile will be used.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// <para>
/// This overload of the <see cref="AddProject{TProject}(IDistributedApplicationBuilder, string)"/> method takes
/// a <typeparamref name="TProject"/> type parameter. The <typeparamref name="TProject"/> type parameter is constrained
/// to types that implement the <see cref="IProjectMetadata"/> interface.
/// </para>
/// <para>
/// Classes that implement the <see cref="IProjectMetadata"/> interface are generated when a .NET project is added as a reference
/// to the app host project. The generated class contains a property that returns the path to the referenced project file. Using this path
/// .NET Aspire parses the <c>launchSettings.json</c> file to determine which launch profile to use when running the project, and
/// what endpoint configuration to automatically generate.
/// </para>
/// <para>
/// The name of the automatically generated project metadata type is a normalized version of the project name. Periods, dashes, and
/// spaces in project names are converted to underscores. This normalization may lead to naming conflicts. If a conflict occurs the <c><ProjectReference /></c>
/// that references the project can have a <c>AspireProjectMetadataTypeName="..."</c> attribute added to override the name.
/// </para>
/// </remarks>
/// <example>
/// Example of adding a project to the application model.
/// <code lang="C#">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddProject<Projects.InventoryService>("inventoryservice", launchProfileName: "otherLaunchProfile");
///
/// builder.Build().Run();
/// </code>
/// </example>
public static IResourceBuilder<ProjectResource> AddProject<TProject>(this IDistributedApplicationBuilder builder, string name, string? launchProfileName) where TProject : IProjectMetadata, new()
{
var project = new ProjectResource(name);
return builder.AddResource(project)
.WithAnnotation(new TProject())
.WithProjectDefaults(excludeLaunchProfile: launchProfileName is null, launchProfileName);
}
/// <summary>
/// Adds a .NET project to the application model.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <param name="name">The name of the resource. This name will be used for service discovery when referenced in a dependency.</param>
/// <param name="projectPath">The path to the project file.</param>
/// <param name="launchProfileName">The launch profile to use. If <c>null</c> then no launch profile will be used.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// <para>
/// This overload of the <see cref="AddProject(IDistributedApplicationBuilder, string, string)"/> method adds a project to the application
/// model using an path to the project file. This allows for projects to be referenced that may not be part of the same solution. If the project
/// path is not an absolute path then it will be computed relative to the app host directory.
/// </para>
/// </remarks>
/// <example>
/// Add a project to the app model via a project path.
/// <code lang="C#">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddProject("inventoryservice", @"..\InventoryService\InventoryService.csproj", launchProfileName: "otherLaunchProfile");
///
/// builder.Build().Run();
/// </code>
/// </example>
public static IResourceBuilder<ProjectResource> AddProject(this IDistributedApplicationBuilder builder, string name, string projectPath, string? launchProfileName)
{
var project = new ProjectResource(name);
projectPath = PathNormalizer.NormalizePathForCurrentPlatform(Path.Combine(builder.AppHostDirectory, projectPath));
return builder.AddResource(project)
.WithAnnotation(new ProjectMetadata(projectPath))
.WithProjectDefaults(excludeLaunchProfile: launchProfileName is null, launchProfileName);
}
private static IResourceBuilder<ProjectResource> WithProjectDefaults(this IResourceBuilder<ProjectResource> builder, bool excludeLaunchProfile, string? launchProfileName)
{
// We only want to turn these on for .NET projects, ConfigureOtlpEnvironment works for any resource type that
// implements IDistributedApplicationResourceWithEnvironment.
builder.WithEnvironment("OTEL_DOTNET_EXPERIMENTAL_OTLP_EMIT_EXCEPTION_LOG_ATTRIBUTES", "true");
builder.WithEnvironment("OTEL_DOTNET_EXPERIMENTAL_OTLP_EMIT_EVENT_LOG_ATTRIBUTES", "true");
// .NET SDK has experimental support for retries. Enable with env var.
// https://github.com/open-telemetry/opentelemetry-dotnet/pull/5495
// Remove once retry feature in opentelemetry-dotnet is enabled by default.
builder.WithEnvironment("OTEL_DOTNET_EXPERIMENTAL_OTLP_RETRY", "in_memory");
// OTEL settings that are used to improve local development experience.
if (builder.ApplicationBuilder.ExecutionContext.IsRunMode && builder.ApplicationBuilder.Environment.IsDevelopment())
{
// Disable URL query redaction, e.g. ?myvalue=Redacted
builder.WithEnvironment("OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION", "true");
builder.WithEnvironment("OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION", "true");
}
builder.WithOtlpExporter();
builder.ConfigureConsoleLogs();
builder.SetAspNetCoreUrls();
var projectResource = builder.Resource;
if (builder.ApplicationBuilder.ExecutionContext.IsPublishMode)
{
builder.WithEnvironment(context =>
{
// If we have any endpoints & the forwarded headers wasn't disabled then add it
if (projectResource.GetEndpoints().Any() && !projectResource.Annotations.OfType<DisableForwardedHeadersAnnotation>().Any())
{
context.EnvironmentVariables[AspNetCoreForwaredHeadersEnabledVariableName] = "true";
}
});
}
if (excludeLaunchProfile)
{
builder.WithAnnotation(new ExcludeLaunchProfileAnnotation());
return builder;
}
if (!string.IsNullOrEmpty(launchProfileName))
{
builder.WithAnnotation(new LaunchProfileAnnotation(launchProfileName));
}
if (builder.ApplicationBuilder.ExecutionContext.IsRunMode)
{
// Process the launch profile and turn it into environment variables and endpoints.
var launchProfile = projectResource.GetEffectiveLaunchProfile(throwIfNotFound: true);
if (launchProfile is null)
{
return builder;
}
var urlsFromApplicationUrl = launchProfile.ApplicationUrl?.Split(';', StringSplitOptions.RemoveEmptyEntries) ?? [];
foreach (var url in urlsFromApplicationUrl)
{
var uri = new Uri(url);
builder.WithEndpoint(uri.Scheme, e =>
{
e.Port = uri.Port;
e.UriScheme = uri.Scheme;
e.FromLaunchProfile = true;
},
createIfNotExists: true);
}
builder.WithEnvironment(context =>
{
// Populate DOTNET_LAUNCH_PROFILE environment variable for consistency with "dotnet run" and "dotnet watch".
context.EnvironmentVariables.TryAdd("DOTNET_LAUNCH_PROFILE", launchProfileName!);
foreach (var envVar in launchProfile.EnvironmentVariables)
{
var value = Environment.ExpandEnvironmentVariables(envVar.Value);
context.EnvironmentVariables.TryAdd(envVar.Key, value);
}
});
// NOTE: the launch profile command line arguments will be processed by ApplicationExecutor.PrepareProjectExecutables() (either by the IDE or manually passed to run)
}
else
{
// If we aren't a web project we don't automatically add bindings.
if (!IsWebProject(projectResource))
{
return builder;
}
var isHttp2ConfiguredInAppSettings = IsKestrelHttp2ConfigurationPresent(projectResource);
if (!projectResource.Annotations.OfType<EndpointAnnotation>().Any(sb => sb.UriScheme == "http" || string.Equals(sb.Name, "http", StringComparisons.EndpointAnnotationName)))
{
builder.WithEndpoint("http", e =>
{
e.UriScheme = "http";
e.Transport = isHttp2ConfiguredInAppSettings ? "http2" : e.Transport;
},
createIfNotExists: true);
}
if (!projectResource.Annotations.OfType<EndpointAnnotation>().Any(sb => sb.UriScheme == "https" || string.Equals(sb.Name, "https", StringComparisons.EndpointAnnotationName)))
{
builder.WithEndpoint("https", e =>
{
e.UriScheme = "https";
e.Transport = isHttp2ConfiguredInAppSettings ? "http2" : e.Transport;
},
createIfNotExists: true);
}
}
return builder;
}
/// <summary>
/// Configures how many replicas of the project should be created for the project.
/// </summary>
/// <param name="builder">The project resource builder.</param>
/// <param name="replicas">The number of replicas.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// <para>
/// When this method is applied to a project resource it will configure the app host to start multiple instances
/// of the application based on the specified number of replicas. By default the app host automatically starts a
/// reverse proxy for each process. When <see cref="WithReplicas(IResourceBuilder{ProjectResource}, int)"/> is
/// used the reverse proxy will load balance traffic between the replicas.
/// </para>
/// <para>
/// This capability can be useful when debugging scale out scenarios to ensure state is appropriately managed
/// within a cluster of instances.
/// </para>
/// </remarks>
/// <example>
/// Start multiple instances of the same service.
/// <code lang="C#">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddProject<Projects.InventoryService>("inventoryservice")
/// .WithReplicas(3);
/// </code>
/// </example>
public static IResourceBuilder<ProjectResource> WithReplicas(this IResourceBuilder<ProjectResource> builder, int replicas)
{
builder.WithAnnotation(new ReplicaAnnotation(replicas));
return builder;
}
/// <summary>
/// Configures the project to disable forwarded headers when being published.
/// </summary>
/// <param name="builder">The project resource builder.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <remarks>
/// <para>
/// By default .NET Aspire assumes that .NET applications which expose endpoints should be configured to
/// use forwarded headers. This is because most typical cloud native deployment scenarios involve a reverse
/// proxy which translates an external endpoint hostname to an internal address.
/// </para>
/// <para>
/// To enable forwarded headers the <c>ASPNETCORE_FORWARDEDHEADERS_ENABLED</c> variable is injected
/// into the project and set to true. If the <see cref="DisableForwardedHeaders(IResourceBuilder{ProjectResource})"/>
/// extension is used this environment variable will not be set.
/// </para>
/// </remarks>
/// <example>
/// Disable forwarded headers for a project.
/// <code lang="C#">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// builder.AddProject<Projects.InventoryService>("inventoryservice")
/// .DisableForwardedHeaders();
/// </code>
/// </example>
public static IResourceBuilder<ProjectResource> DisableForwardedHeaders(this IResourceBuilder<ProjectResource> builder)
{
builder.WithAnnotation<DisableForwardedHeadersAnnotation>(ResourceAnnotationMutationBehavior.Replace);
return builder;
}
private static bool IsKestrelHttp2ConfigurationPresent(ProjectResource projectResource)
{
var projectMetadata = projectResource.GetProjectMetadata();
var projectDirectoryPath = Path.GetDirectoryName(projectMetadata.ProjectPath)!;
var appSettingsPath = Path.Combine(projectDirectoryPath, "appsettings.json");
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
var appSettingsEnvironmentPath = Path.Combine(projectDirectoryPath, $"appsettings.{env}.json");
var configBuilder = new ConfigurationBuilder();
configBuilder.AddJsonFile(appSettingsPath, optional: true);
configBuilder.AddJsonFile(appSettingsEnvironmentPath, optional: true);
var config = configBuilder.Build();
var protocol = config["Kestrel:EndpointDefaults:Protocols"];
return protocol == "Http2";
}
private static bool IsWebProject(ProjectResource projectResource)
{
var launchProfile = projectResource.GetEffectiveLaunchProfile(throwIfNotFound: true);
return launchProfile?.ApplicationUrl != null;
}
private static void SetAspNetCoreUrls(this IResourceBuilder<ProjectResource> builder)
{
if (builder.ApplicationBuilder.ExecutionContext.IsPublishMode)
{
return;
}
builder.WithEnvironment(context =>
{
if (context.EnvironmentVariables.ContainsKey("ASPNETCORE_URLS"))
{
// If the user has already set ASPNETCORE_URLS, we don't want to override it.
return;
}
var aspnetCoreUrls = new ReferenceExpressionBuilder();
var processedHttpsPort = false;
var first = true;
static bool IsValidAspNetCoreUrl(EndpointAnnotation e) =>
e.UriScheme is "http" or "https" && e.TargetPortEnvironmentVariable is null;
// Turn http and https endpoints into a single ASPNETCORE_URLS environment variable.
foreach (var e in builder.Resource.GetEndpoints().Where(e => IsValidAspNetCoreUrl(e.EndpointAnnotation)))
{
if (!first)
{
aspnetCoreUrls.AppendLiteral(";");
}
if (!processedHttpsPort && e.EndpointAnnotation.UriScheme == "https")
{
// Add the environment variable for the HTTPS port if we have an HTTPS service. This will make sure the
// HTTPS redirection middleware avoids redirecting to the internal port.
context.EnvironmentVariables["ASPNETCORE_HTTPS_PORT"] = e.Property(EndpointProperty.Port);
processedHttpsPort = true;
}
aspnetCoreUrls.Append($"{e.Property(EndpointProperty.Scheme)}://localhost:{e.Property(EndpointProperty.TargetPort)}");
first = false;
}
if (!aspnetCoreUrls.IsEmpty)
{
// Combine into a single expression
context.EnvironmentVariables["ASPNETCORE_URLS"] = aspnetCoreUrls.Build();
}
});
}
}