-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
145 lines (125 loc) · 6.5 KB
/
Program.cs
File metadata and controls
145 lines (125 loc) · 6.5 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
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using LlrpApi.Data;
using LlrpApi.Middleware;
using LlrpApi.Options;
using LlrpApi.Services;
using LlrpApi.Swagger;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
// ── Options ──────────────────────────────────────────────────────────────────
builder.Services.Configure<DatabaseOptions>(builder.Configuration.GetSection(DatabaseOptions.SectionName));
builder.Services.Configure<StorageOptions>(builder.Configuration.GetSection(StorageOptions.SectionName));
builder.Services.Configure<ApiKeyOptions>(builder.Configuration.GetSection(ApiKeyOptions.SectionName));
// ── Database ─────────────────────────────────────────────────────────────────
builder.Services.AddDbContext<AppDbContext>((sp, opt) =>
{
var dbOptions = sp.GetRequiredService<IOptions<DatabaseOptions>>().Value;
if (dbOptions.Provider.Equals("sqlite", StringComparison.OrdinalIgnoreCase))
opt.UseSqlite(dbOptions.BuildConnectionString());
else
opt.UseNpgsql(dbOptions.BuildConnectionString());
});
// ── Application services ──────────────────────────────────────────────────────
builder.Services.AddScoped<FileQueryService>();
builder.Services.AddScoped<SeedService>();
builder.Services.AddSingleton<CroissantBuilder>();
// ── File storage (local disk or S3-compatible blob store) ─────────────────────
var storageOptions = builder.Configuration.GetSection(StorageOptions.SectionName).Get<StorageOptions>() ?? new();
if (storageOptions.Provider.Equals("s3", StringComparison.OrdinalIgnoreCase))
builder.Services.AddSingleton<IFileStorageService, S3FileStorageService>();
else
builder.Services.AddSingleton<IFileStorageService, LocalFileStorageService>();
// ── Controllers ───────────────────────────────────────────────────────────────
builder.Services.AddControllers();
// ── Swagger / OpenAPI ─────────────────────────────────────────────────────────
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Low Resource Language Library API",
Version = "v1",
Description = """
Query the Low Resource Language Library catalogue and receive
**Croissant 1.0 JSON-LD** responses ready for ML dataset tooling.
All endpoints require an `X-Api-Key` header.
Click **Authorize** and enter your key to authenticate within Swagger UI.
""",
Contact = new OpenApiContact
{
Name = "DDP Data Access",
Email = "data@datapartnership.org",
Url = new Uri("https://datapartnership.org/contact")
}
});
// Register the X-Api-Key security scheme
c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Header,
Name = "X-Api-Key",
Description = "Enter your API key. Keys are managed in appsettings.json → ApiKeys."
});
// Apply the scheme globally so every endpoint shows the lock icon
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "ApiKey"
}
},
[]
}
});
// Include XML comments from the project (controllers + DTOs)
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
c.IncludeXmlComments(xmlPath);
// Inject realistic Croissant JSON-LD examples into Swagger UI
c.OperationFilter<CroissantExampleFilter>();
});
// ── Build ─────────────────────────────────────────────────────────────────────
var app = builder.Build();
// ── Middleware pipeline ───────────────────────────────────────────────────────
// Swagger UI is served before the API-key gate so the UI itself is accessible
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "LRLL API v1");
c.RoutePrefix = "swagger";
c.DocumentTitle = "Low Resource Language Library API";
c.DefaultModelsExpandDepth(-1); // hide schema section by default
c.DisplayRequestDuration();
});
// API key enforcement (Swagger paths are exempt inside the middleware)
app.UseMiddleware<ApiKeyMiddleware>();
//app.UseHttpsRedirection();
app.MapControllers();
// ── Ensure DB exists on startup ───────────────────────────────────────────────
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
var dbOptions = scope.ServiceProvider.GetRequiredService<IOptions<DatabaseOptions>>().Value;
db.Database.EnsureCreated();
try
{
var canConnect = await db.Database.CanConnectAsync();
if (canConnect)
logger.LogInformation("Database connected successfully (provider: {Provider}).", dbOptions.Provider);
else
logger.LogWarning("Database connection check failed (provider: {Provider}).", dbOptions.Provider);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to connect to database (provider: {Provider}).", dbOptions.Provider);
}
}
app.Run();