Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
209 lines (182 loc) · 7.11 KB
/
Copy pathProgram.cs
File metadata and controls
209 lines (182 loc) · 7.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
using System.Text;
using FluentValidation;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using ProcessAnalyzerApi.Data;
using ProcessAnalyzerApi.Middleware;
using ProcessAnalyzerApi.Services;
using ProcessAnalyzerApi.Validators;
using Serilog;
// Configure Serilog
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File("logs/process-analyzer-.log", rollingInterval: RollingInterval.Day)
.CreateLogger();
try
{
Log.Information("Starting Process Analyzer API");
var builder = WebApplication.CreateBuilder(args);
// Use Serilog for logging
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File("logs/process-analyzer-.log", rollingInterval: RollingInterval.Day));
// Add services to the container
builder.Services.AddControllers();
// CORS Configuration
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// FluentValidation
builder.Services.AddValidatorsFromAssemblyContaining<AnalyzeRequestDtoValidator>();
// JWT Authentication
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var secretKey = jwtSettings["SecretKey"] ?? "YourSuperSecretKeyThatShouldBeAtLeast32CharactersLong!";
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSettings["Issuer"] ?? "ProcessAnalyzerApi",
ValidAudience = jwtSettings["Audience"] ?? "ProcessAnalyzerApi",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
};
});
// Swagger/OpenAPI with enhanced documentation and JWT support
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Process Analyzer API",
Version = "v1",
Description = "AI-powered business process analysis REST API. Analyze business processes and get intelligent recommendations for automation and optimization.",
Contact = new OpenApiContact
{
Name = "API Support",
Email = "support@example.com"
},
License = new OpenApiLicense
{
Name = "MIT License"
}
});
// Add JWT Authentication to Swagger
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
// Include XML comments in Swagger
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
{
c.IncludeXmlComments(xmlPath);
}
});
// Rate Limiting (using built-in .NET 8 rate limiting)
builder.Services.AddRateLimiter(options =>
{
options.GlobalLimiter = System.Threading.RateLimiting.PartitionedRateLimiter.Create<HttpContext, string>(context =>
System.Threading.RateLimiting.RateLimitPartition.GetFixedWindowLimiter(
partitionKey: context.Connection.RemoteIpAddress?.ToString() ?? "anonymous",
factory: partition => new System.Threading.RateLimiting.FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 60,
Window = TimeSpan.FromMinutes(1)
}));
});
// Database
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
// HTTP Client for LLM
builder.Services.AddHttpClient<ILlmService, LlmService>();
// Application services
builder.Services.AddScoped<IAnalysisService, AnalysisService>();
builder.Services.AddScoped<IAuthService, AuthService>();
// Health Checks - register the health check class
builder.Services.AddTransient<AppDbContextHealthCheck>();
builder.Services.AddHealthChecks()
.AddCheck<AppDbContextHealthCheck>("database");
var app = builder.Build();
// Global exception handler middleware (must be first)
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
// Rate Limiting
app.UseRateLimiter();
// CORS
app.UseCors("AllowAll");
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Process Analyzer API v1");
c.RoutePrefix = string.Empty; // Set Swagger UI at the app's root
c.DisplayRequestDuration();
c.EnableDeepLinking();
c.EnableFilter();
});
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Health Check endpoint
app.MapHealthChecks("/health");
// Ensure database is created and migrations are applied
using (var scope = app.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
context.Database.Migrate();
}
Log.Information("Process Analyzer API started successfully");
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}