-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
244 lines (217 loc) · 11 KB
/
Program.cs
File metadata and controls
244 lines (217 loc) · 11 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
using System.Text;
using FluentValidation;
using MassTransit;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using Serilog;
using Serilog.Events;
using TradeTrac.OrderService.API.Controllers;
using TradeTrac.OrderService.API.Middleware;
using TradeTrac.OrderService.Application.Behaviours;
using TradeTrac.OrderService.Application.Commands;
using TradeTrac.OrderService.Application.Queries;
using TradeTrac.OrderService.Domain.Repositories;
using TradeTrac.OrderService.Infrastructure.Messaging;
using TradeTrac.OrderService.Infrastructure.Persistence;
using TradeTrac.OrderService.Infrastructure.Persistence.Repositories;
// ── Bootstrap Serilog immediately so startup errors are captured ──────────────
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithProperty("Service", "OrderService")
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
.CreateBootstrapLogger();
try
{
var builder = WebApplication.CreateBuilder(args);
// ── Serilog ───────────────────────────────────────────────────────────────
builder.Host.UseSerilog((ctx, services, cfg) => cfg
.ReadFrom.Configuration(ctx.Configuration)
.ReadFrom.Services(services)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithProperty("Service", "OrderService")
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"));
// ── Configuration binding ─────────────────────────────────────────────────
var jwtSection = builder.Configuration.GetSection("Jwt");
builder.Services.Configure<JwtOptions>(jwtSection);
var jwtOptions = jwtSection.Get<JwtOptions>()!;
var connStr = builder.Configuration.GetConnectionString("Orders")
?? throw new InvalidOperationException("ConnectionStrings:Orders is required.");
var rabbitHost = builder.Configuration["RabbitMQ:Host"] ?? "localhost";
var rabbitUser = builder.Configuration["RabbitMQ:Username"] ?? "guest";
var rabbitPass = builder.Configuration["RabbitMQ:Password"] ?? "guest";
var otelEndpoint = builder.Configuration["Otel:Endpoint"] ?? "http://localhost:4317";
// ── EF Core ───────────────────────────────────────────────────────────────
builder.Services.AddDbContext<OrdersDbContext>(opts =>
opts.UseNpgsql(connStr, pg =>
{
pg.EnableRetryOnFailure(3, TimeSpan.FromSeconds(5), null);
pg.CommandTimeout(30);
pg.MigrationsHistoryTable("__ef_migrations", "public");
})
.UseSnakeCaseNamingConvention());
// ── Repository + Unit of Work ─────────────────────────────────────────────
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<OrdersDbContext>());
builder.Services.AddScoped<IOutboxService, OutboxService>();
// Register the connection string for Dapper query handlers
builder.Services.AddSingleton(connStr);
// ── MediatR (CQRS) ────────────────────────────────────────────────────────
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<PlaceOrderCommand>();
cfg.AddOpenBehavior(typeof(LoggingBehaviour<,>));
cfg.AddOpenBehavior(typeof(ValidationBehaviour<,>));
});
// ── FluentValidation ─────────────────────────────────────────────────────
builder.Services.AddValidatorsFromAssemblyContaining<PlaceOrderCommand>();
// ── MassTransit → RabbitMQ ────────────────────────────────────────────────
builder.Services.AddMassTransit(mt =>
{
mt.UsingRabbitMq((ctx, cfg) =>
{
cfg.Host(rabbitHost, h =>
{
h.Username(rabbitUser);
h.Password(rabbitPass);
});
// Publisher confirms — don't consider a message delivered until RabbitMQ confirms
cfg.PublisherConfirmation = true;
cfg.ConfigureEndpoints(ctx);
});
});
// ── Background workers ────────────────────────────────────────────────────
builder.Services.AddHostedService<OutboxPublisherWorker>();
// ── JWT Authentication ────────────────────────────────────────────────────
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opts =>
{
opts.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtOptions.Issuer,
ValidAudience = jwtOptions.Audience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwtOptions.Key))
};
});
builder.Services.AddAuthorization(opts =>
{
opts.AddPolicy("InternalService", p => p.RequireRole("InternalService"));
});
// ── OpenTelemetry ─────────────────────────────────────────────────────────
builder.Services.AddOpenTelemetry()
.ConfigureResource(r => r.AddService("OrderService", serviceVersion: "1.0.0"))
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation(opts =>
{
opts.Filter = ctx => ctx.Request.Path.Value?.StartsWith("/health") != true;
})
.AddEntityFrameworkCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddSource("MassTransit")
.AddOtlpExporter(o => o.Endpoint = new Uri(otelEndpoint)))
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddRuntimeInstrumentation()
.AddOtlpExporter(o => o.Endpoint = new Uri(otelEndpoint)));
// ── Health Checks ─────────────────────────────────────────────────────────
builder.Services.AddHealthChecks()
.AddNpgsql(connStr, name: "postgres", tags: ["db", "ready"])
.AddRabbitMQ(
rabbitConnectionString: $"amqp://{rabbitUser}:{rabbitPass}@{rabbitHost}",
name: "rabbitmq",
tags: ["mq", "ready"]);
// ── Swagger / OpenAPI ─────────────────────────────────────────────────────
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "TradeTrac — Order Service",
Version = "v1",
Description = "Trade order management API. DDD + Clean Architecture + CQRS."
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Enter: Bearer {token}",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
},
Array.Empty<string>()
}
});
});
builder.Services.AddControllers();
// ── Build ─────────────────────────────────────────────────────────────────
var app = builder.Build();
// ── Auto-migrate on startup ───────────────────────────────────────────────
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OrdersDbContext>();
Log.Information("Running database migrations…");
await db.Database.MigrateAsync();
Log.Information("Migrations complete.");
}
// ── Middleware pipeline ───────────────────────────────────────────────────
app.UseMiddleware<ExceptionHandlingMiddleware>();
app.UseSerilogRequestLogging(opts =>
{
opts.MessageTemplate = "HTTP {RequestMethod} {RequestPath} → {StatusCode} ({Elapsed:0.0}ms)";
opts.GetLevel = (ctx, elapsed, ex) => ex != null
? LogEventLevel.Error
: ctx.Response.StatusCode >= 400
? LogEventLevel.Warning
: LogEventLevel.Information;
});
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHealthChecks("/health");
app.MapHealthChecks("/health/ready", new()
{
Predicate = check => check.Tags.Contains("ready")
});
app.MapHealthChecks("/health/live", new()
{
Predicate = _ => false // liveness = just the process is up
});
Log.Information("Order Service starting on {Urls}", app.Urls);
await app.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "Order Service failed to start.");
return 1;
}
finally
{
await Log.CloseAndFlushAsync();
}
return 0;