English
Operations
Step 1. A background cleanup
Why. Two kinds of data pile up without anyone asking for them: uploads that were never sent (topic 11) and refresh tokens that expired or were revoked long ago (topic 8). The services already know how to delete them; something must call them regularly. ASP.NET Core runs hosted services next to the web server — long-running background tasks that start and stop with the application.
Do. Create the folder Maintenance:
cs
using System.ComponentModel.DataAnnotations;
using Chatex.Core.Attachments;
using Chatex.Core.Auth;
using Microsoft.Extensions.Options;
namespace Chatex.Api.Maintenance;
internal sealed class MaintenanceOptions
{
public const string Section = "Maintenance";
public bool Enabled { get; set; } = true;
/// <summary>How often the cleanup runs; the first run is right after startup.</summary>
[Range(typeof(TimeSpan), "00:01:00", "1.00:00:00")]
public TimeSpan Interval { get; set; } = TimeSpan.FromHours(1);
/// <summary>Uploads that were never sent with a message are deleted after this long.</summary>
[Range(typeof(TimeSpan), "00:10:00", "30.00:00:00")]
public TimeSpan StaleUploadAge { get; set; } = TimeSpan.FromHours(24);
}
/// <summary>
/// Deletes uploads that were never sent and refresh tokens that can no longer be used. Each pass runs in its own DI
/// scope, like a request; a failed pass is logged and the next one runs on schedule.
/// </summary>
internal sealed partial class MaintenanceService(
IServiceScopeFactory scopes,
IOptions<MaintenanceOptions> options,
TimeProvider timeProvider,
ILogger<MaintenanceService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var settings = options.Value;
if (!settings.Enabled)
{
return;
}
using var timer = new PeriodicTimer(settings.Interval, timeProvider);
do
{
await RunOnceAsync(settings, stoppingToken);
}
while (await timer.WaitForNextTickAsync(stoppingToken));
}
private async Task RunOnceAsync(MaintenanceOptions settings, CancellationToken cancellationToken)
{
try
{
await using var scope = scopes.CreateAsyncScope();
var attachments = scope.ServiceProvider.GetRequiredService<IAttachmentService>();
var auth = scope.ServiceProvider.GetRequiredService<IAuthService>();
var uploads = 0;
int batch;
do
{
batch = await attachments.CleanupStaleAsync(settings.StaleUploadAge, cancellationToken);
uploads += batch;
}
while (batch > 0);
var tokens = await auth.DeleteStaleRefreshTokensAsync(cancellationToken);
if (uploads > 0 || tokens > 0)
{
LogCleaned(uploads, tokens);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogFailed(ex);
}
}
[LoggerMessage(Level = LogLevel.Information, Message = "Maintenance deleted {Uploads} stale uploads and {Tokens} stale refresh tokens")]
private partial void LogCleaned(int uploads, int tokens);
[LoggerMessage(Level = LogLevel.Error, Message = "Maintenance pass failed; the next one runs on schedule")]
private partial void LogFailed(Exception exception);
}BackgroundServiceis the base class for a hosted service: overrideExecuteAsync, which runs until the application stops (stoppingToken).PeriodicTimerwith the injectedTimeProviderticks every hour; the first pass runs right after start-up (do … while).- A new scope per pass: the services are scoped (one
DbContextper unit of work), and a background service has no request scope.IServiceScopeFactorycreates one, exactly like a request would. - Uploads are cleaned in batches of 500 until a batch comes back empty.
- A failed pass is logged, not fatal: the database may be briefly unavailable; the next pass runs on schedule.
OperationCanceledExceptionis excluded, so shutting down is not logged as an error. [LoggerMessage]onpartialmethods lets the compiler generate fast, structured logging methods; the placeholders{Uploads}and{Tokens}become named properties in the log.
Step 2. Register the rest of the web layer
Why. AddApi gets everything this topic introduced, plus two things a server behind a proxy needs.
- Forwarded headers. Behind Nginx, Kestrel sees every request from
127.0.0.1over plain HTTP. Nginx addsX-Forwarded-For(the client's IP) andX-Forwarded-Proto(https); the forwarded headers middleware puts them back intoHttpContext.Connection.RemoteIpAddressandRequest.Scheme. Rate limiting and the IP stored with refresh tokens depend on it. - Data Protection is ASP.NET Core's key ring for encrypting short-lived data (for example Identity's password reset tokens). Its keys must survive a restart, so on the server they are written to a folder (
DataProtection:KeysPath); without the setting they live in memory.
Do. Extend AddApi (new lines in green):
cs
using System.Text.Json;
using System.Text.Json.Serialization;
using Chatex.Api.Infrastructure;
using Chatex.Api.Maintenance;
using Chatex.Core.Auth;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace Chatex.Api;
public static class DependencyInjection
{
/// <summary>The request body limit for everything except file uploads.</summary>
public const long MaxRequestBodyBytes = 1024 * 1024;
public static IServiceCollection AddApi(this IServiceCollection services, IConfiguration configuration)
{
// Without a key folder the keys live in memory and change on every restart. Nothing persistent depends on
// them yet, but Identity tokens (password reset, email confirmation) will.
var dataProtection = services.AddDataProtection().SetApplicationName("Chatex");
if (configuration["DataProtection:KeysPath"] is { Length: > 0 } keysPath)
{
dataProtection.PersistKeysToFileSystem(new DirectoryInfo(keysPath));
}
services.AddOptions<MaintenanceOptions>()
.BindConfiguration(MaintenanceOptions.Section)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddHostedService<MaintenanceService>();
// JSON bodies are small; the upload endpoints raise this per request (FileUploadExtensions.AcceptsFileUpTo).
services.Configure<KestrelServerOptions>(o => o.Limits.MaxRequestBodySize = MaxRequestBodyBytes);
services.ConfigureHttpJsonOptions(o =>
o.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)));
services.AddProblemDetails();
services.AddChatexRateLimiting();
// Malformed bodies answer 400 (turned into problem details by UseStatusCodePages) in every environment,
// instead of throwing to the exception handler in Development.
services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = false);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<JwtOptions>>((bearer, jwtOptions) =>
{
var jwt = jwtOptions.Value;
bearer.MapInboundClaims = false;
bearer.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwt.Issuer,
ValidAudience = jwt.Audience,
IssuerSigningKey = jwt.CreateSigningKey(),
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
NameClaimType = JwtRegisteredClaimNames.UniqueName,
ClockSkew = TimeSpan.FromSeconds(30),
};
});
services.AddAuthorization();
services.Configure<ForwardedHeadersOptions>(o =>
o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto);
services.AddOpenApi(o =>
{
o.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
o.AddOperationTransformer<BearerSecuritySchemeTransformer>();
});
return services;
}
}MaxRequestBodyBytesis public, so anyone can see the global limit of 1 MB;Configure<KestrelServerOptions>sets it, andAcceptsFileUpToraises it for the upload endpoints.AddHostedService<MaintenanceService>()starts the cleanup with the application; its options (Enabled,Interval,StaleUploadAge) are validated at start.BindConfigurationis a shorter form ofBind(configuration.GetSection(...)).AddChatexRateLimiting()is the extension method of the previous chapter.
Step 3. The final pipeline
Do. Extend Program.cs (new lines in green):
cs
using Chatex.Api;
using Chatex.Api.Endpoints;
using Chatex.Api.Infrastructure;
using Chatex.Core;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddApi(builder.Configuration);
builder.Services.AddCore(builder.Configuration);
var app = builder.Build();
app.UseForwardedHeaders();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference(o => o.AddPreferredSecuritySchemes(BearerSecuritySchemeTransformer.SchemeName));
}
// Readiness: 200 when the API can reach the database, 503 otherwise (the deploy rolls back on 503).
app.MapHealthChecks("/health").AllowAnonymous();
var api = app.MapGroup("/api").RequireAuthorization();
api.MapAuthEndpoints();
api.MapProfileEndpoints();
api.MapUserEndpoints();
api.MapChatEndpoints();
api.MapMessageEndpoints();
api.MapAttachmentEndpoints();
app.Run();
/// <summary>Visible to <c>WebApplicationFactory</c> in the Api tests.</summary>
public partial class Program;UseForwardedHeaderscomes first, so every later middleware sees the real client.UseRateLimitercomes after authentication: a policy could then partition by user; Chatex partitions by IP.MapHealthChecks("/health").AllowAnonymous()answers200 Healthywhen the database check of topic 5 passes and503 Unhealthyotherwise — without a token, because the deployment script (topic 24) and monitoring tools call it.MapAttachmentEndpointsmaps the upload and download endpoints.
Step 4. Production settings
Why. On the server the API runs as a systemd service (topic 23); its console output goes to the system journal. The systemd console formatter writes one line per entry with a severity prefix that journalctl understands, instead of the colored multi-line format of development.
Do.
json
{
"Logging": {
"Console": {
"FormatterName": "systemd"
}
}
}Everything else for production — the connection string, the signing key, the upload and key folders — comes from environment variables on the server (Jwt__SigningKey, with a double underscore for the : of a section), never from a file in the repository.
Check
dotnet build succeeds. Run the API (./Run.ps1 api) and open http://localhost:5214/health: the page shows Healthy. Stop the database with ./Run.ps1 db-stop and reload: within a few seconds the answer is 503 with Unhealthy. Start it again with ./Run.ps1 db.