Repository navigation
Expand file tree
/
Copy pathSimpleModuleHostExtensions.cs
More file actions
267 lines (229 loc) · 9.44 KB
/
Copy pathSimpleModuleHostExtensions.cs
File metadata and controls
267 lines (229 loc) · 9.44 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
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
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SimpleModule.Blazor;
using SimpleModule.Core.Constants;
using SimpleModule.Core.Events;
using SimpleModule.Core.Exceptions;
using SimpleModule.Core.Inertia;
using SimpleModule.Core.Menu;
using SimpleModule.Database;
using SimpleModule.Database.Health;
using SimpleModule.Database.Interceptors;
using SimpleModule.DevTools;
namespace SimpleModule.Hosting;
public static class SimpleModuleHostExtensions
{
private const int ImmutableAssetsCacheDurationSeconds = 31536000; // 365 days
private const string VendorJsPathPrefix = "/js/vendor/";
private const string ModuleContentPathPrefix = "/_content/";
private const string ModuleScriptExtension = ".mjs";
/// <summary>
/// Registers all non-generated SimpleModule infrastructure services.
/// Called by the source-generated <c>AddSimpleModule()</c> method.
/// </summary>
public static WebApplicationBuilder AddSimpleModuleInfrastructure(
this WebApplicationBuilder builder,
Action<SimpleModuleOptions>? configure = null
)
{
var options = new SimpleModuleOptions();
configure?.Invoke(options);
builder.Services.AddSingleton(options);
BridgeAspireConnectionString(builder.Configuration);
ValidateDatabaseConfiguration(builder.Configuration);
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
if (options.EnableSwagger)
{
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
}
builder.Services.AddRazorComponents();
if (options.ShellComponent is not null)
{
builder.Services.AddSimpleModuleBlazor(o => o.ShellComponent = options.ShellComponent);
}
else
{
builder.Services.AddSimpleModuleBlazor();
}
builder.Services.AddSingleton<BackgroundEventChannel>();
builder.Services.AddHostedService<BackgroundEventDispatcher>();
builder.Services.AddScoped<IEventBus, EventBus>();
builder.Services.AddScoped<InertiaSharedData>();
// Entity framework interceptors for automatic entity field population
builder.Services.AddScoped<ISaveChangesInterceptor, EntityInterceptor>();
builder.Services.AddScoped<ISaveChangesInterceptor, DomainEventInterceptor>();
builder.Services.AddScoped<ISaveChangesInterceptor, EntityChangeInterceptor>();
// Authentication is configured by modules via their ConfigureServices
// (e.g., OpenIddict registers SmartAuth policy scheme).
// Register a baseline so the middleware pipeline works even without an auth module.
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
// Register default IPublicMenuProvider if no module provides one
builder.Services.TryAddScoped<IPublicMenuProvider, DefaultPublicMenuProvider>();
if (options.EnableHealthChecks)
{
builder
.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>(
HealthCheckConstants.DatabaseCheckName,
tags: [HealthCheckConstants.ReadyTag]
);
}
if (options.EnableDevTools && builder.Environment.IsDevelopment())
{
builder.Services.AddDevTools();
}
return builder;
}
/// <summary>
/// Configures all non-generated SimpleModule middleware.
/// Called by the source-generated <c>UseSimpleModule()</c> method.
/// </summary>
public static async Task UseSimpleModuleInfrastructure(this WebApplication app)
{
// Database initialization (non-production only)
if (!app.Environment.IsProduction())
{
using var scope = app.Services.CreateScope();
var infos = scope.ServiceProvider.GetServices<ModuleDbContextInfo>();
foreach (var info in infos)
{
if (info.ModuleName != DatabaseConstants.HostModuleName)
continue;
if (scope.ServiceProvider.GetService(info.DbContextType) is DbContext db)
{
await db.Database.MigrateAsync();
}
}
}
app.UseExceptionHandler();
var options = app.Services.GetRequiredService<SimpleModuleOptions>();
if (options.EnableSwagger && app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseInertia();
UseStaticFileCaching(app);
app.MapStaticAssets();
// Fallback for dynamically generated .mjs chunks (Vite watch rebuilds)
// MapStaticAssets only knows about files present at build time;
// Vite generates new hash-named chunks at runtime that need correct MIME types
if (app.Environment.IsDevelopment())
{
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".mjs"] = "application/javascript";
app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider });
}
app.UseAuthentication();
app.UseAuthorization();
// Module middleware is added by the source-generated UseSimpleModule()
// via IModule.ConfigureMiddleware() calls.
UseHomePageRewrite(app);
app.UseAntiforgery();
if (options.EnableHealthChecks)
{
app.MapHealthChecks(
RouteConstants.HealthLive,
new HealthCheckOptions { Predicate = _ => false }
)
.AllowAnonymous();
app.MapHealthChecks(
RouteConstants.HealthReady,
new HealthCheckOptions
{
Predicate = check => check.Tags.Contains(HealthCheckConstants.ReadyTag),
}
)
.AllowAnonymous();
}
}
private static void BridgeAspireConnectionString(ConfigurationManager configuration)
{
var aspireConnectionString = configuration.GetConnectionString("simplemoduledb");
if (!string.IsNullOrEmpty(aspireConnectionString))
{
configuration["Database:DefaultConnection"] = aspireConnectionString;
}
}
private static void ValidateDatabaseConfiguration(ConfigurationManager configuration)
{
var dbOptions =
configuration.GetSection(DatabaseConstants.SectionName).Get<DatabaseOptions>()
?? new DatabaseOptions();
var connString = dbOptions.DefaultConnection;
if (string.IsNullOrEmpty(connString))
{
throw new InvalidOperationException(
"Database configuration is missing. "
+ "Ensure 'Database:DefaultConnection' is configured in appsettings.json."
);
}
_ = DatabaseProviderDetector.Detect(connString, dbOptions.Provider);
}
private static void UseStaticFileCaching(WebApplication app)
{
app.Use(
async (context, next) =>
{
var path = context.Request.Path.Value;
if (string.IsNullOrEmpty(path))
{
await next();
return;
}
bool hasVersionParam = context.Request.Query.ContainsKey("v");
bool isVendorJs = path.StartsWith(
VendorJsPathPrefix,
StringComparison.OrdinalIgnoreCase
);
bool isHashedChunk =
path.StartsWith(ModuleContentPathPrefix, StringComparison.OrdinalIgnoreCase)
&& path.EndsWith(ModuleScriptExtension, StringComparison.OrdinalIgnoreCase);
if (hasVersionParam || isVendorJs || isHashedChunk)
{
context.Response.OnStarting(() =>
{
context.Response.Headers.CacheControl =
$"public, max-age={ImmutableAssetsCacheDurationSeconds}, immutable";
return Task.CompletedTask;
});
}
await next();
}
);
}
private static void UseHomePageRewrite(WebApplication app)
{
app.Use(
async (context, next) =>
{
if (context.Request.Path == "/" && HttpMethods.IsGet(context.Request.Method))
{
var menuProvider = context.RequestServices.GetService<IPublicMenuProvider>();
if (menuProvider is not null)
{
var homeUrl = await menuProvider.GetHomePageUrlAsync();
if (homeUrl is not null && homeUrl != "/")
{
context.Request.Path = homeUrl;
}
}
}
await next();
}
);
}
}