Foxnouns.NET/Foxnouns.Backend/Program.cs

88 lines
2.5 KiB
C#
Raw Normal View History

using Foxnouns.Backend;
2024-05-27 15:53:54 +02:00
using Foxnouns.Backend.Extensions;
using Foxnouns.Backend.Services;
using Foxnouns.Backend.Utils;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
2024-05-27 15:53:54 +02:00
using Newtonsoft.Json.Serialization;
using Prometheus;
using Sentry.Extensibility;
using Serilog;
2024-05-27 15:53:54 +02:00
var builder = WebApplication.CreateBuilder(args);
var config = builder.AddConfiguration();
builder.AddSerilog();
2024-05-27 15:53:54 +02:00
builder
.WebHost.UseSentry(opts =>
{
opts.Dsn = config.Logging.SentryUrl;
opts.TracesSampleRate = config.Logging.SentryTracesSampleRate;
opts.MaxRequestBodySize = RequestSize.Small;
})
.ConfigureKestrel(opts =>
{
// Requests are limited to a maximum of 2 MB.
// No valid request body will ever come close to this limit,
// but the limit is slightly higher to prevent valid requests from being rejected.
opts.Limits.MaxRequestBodySize = 2 * 1024 * 1024;
});
builder
.Services.AddControllers()
2024-05-27 15:53:54 +02:00
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new PatchRequestContractResolver
2024-05-27 15:53:54 +02:00
{
NamingStrategy = new SnakeCaseNamingStrategy(),
};
})
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = actionContext => new BadRequestObjectResult(
new ApiError.AspBadRequest("Bad request", actionContext.ModelState).ToJson()
);
});
2024-05-27 15:53:54 +02:00
// Set the default converter to snake case as we use it in a couple places.
JsonConvert.DefaultSettings = () =>
new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy(),
},
};
builder.AddServices(config).AddCustomMiddleware().AddEndpointsApiExplorer().AddSwaggerGen();
2024-05-27 15:53:54 +02:00
var app = builder.Build();
await app.Initialize(args);
2024-05-27 15:53:54 +02:00
app.UseSerilogRequestLogging();
app.UseRouting();
// Not all environments will want tracing (from experience, it's expensive to use in production, even with a low sample rate),
// so it's locked behind a config option.
if (config.Logging.SentryTracing)
app.UseSentryTracing();
2024-05-27 15:53:54 +02:00
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors();
app.UseCustomMiddleware();
2024-05-27 15:53:54 +02:00
app.MapControllers();
app.Urls.Clear();
app.Urls.Add(config.Address);
// Make sure metrics are updated whenever Prometheus scrapes them
Metrics.DefaultRegistry.AddBeforeCollectCallback(async ct =>
await app.Services.GetRequiredService<MetricsCollectionService>().CollectMetricsAsync(ct)
);
2024-05-27 15:53:54 +02:00
app.Run();
Log.CloseAndFlush();