-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathProgram.cs
More file actions
202 lines (176 loc) · 7.24 KB
/
Program.cs
File metadata and controls
202 lines (176 loc) · 7.24 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
using System.Reflection;
using Serilog.Sinks.File.Header;
using TaikoLocalServer.Adapters.AdminApi;
using TaikoLocalServer.Adapters.AdminApi.Controllers;
using TaikoLocalServer.Adapters.AllnetMucha;
using TaikoLocalServer.Adapters.GameProtocol.CnR00;
using TaikoLocalServer.Adapters.GameProtocol.WwR08;
using TaikoLocalServer.Application;
using TaikoLocalServer.Infrastructure;
using TaikoLocalServer.Infrastructure.Persistence;
using TaikoLocalServer.Logging;
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.AspNetCore.HttpOverrides;
using Throw;
using Serilog;
using Microsoft.AspNetCore.ResponseCompression;
using System.IO.Compression;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
var version = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
.InformationalVersion;
Log.Information("TaikoLocalServer version {Version}", version);
var buildTime = Assembly.GetEntryAssembly()?
.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(attr => attr.Key == "BuildTime")?.Value;
if (buildTime != null)
{
Log.Information("Build time: {BuildTime}", buildTime);
}
Log.Information("Server starting up...");
try
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpLogging(options =>
{
options.LoggingFields = HttpLoggingFields.All;
options.RequestBodyLogLimit = 32768;
options.ResponseBodyLogLimit = 32768;
});
const string configurationsDirectory = "Configurations";
builder.Configuration.AddJsonFile($"{configurationsDirectory}/Kestrel.json", optional: true, reloadOnChange: false);
builder.Configuration.AddJsonFile($"{configurationsDirectory}/Logging.json", optional: false, reloadOnChange: false);
builder.Configuration.AddJsonFile($"{configurationsDirectory}/Database.json", optional: false, reloadOnChange: false);
builder.Configuration.AddJsonFile($"{configurationsDirectory}/ServerSettings.json", optional: false, reloadOnChange: false);
builder.Configuration.AddJsonFile($"{configurationsDirectory}/DataSettings.json", optional: true, reloadOnChange: false);
builder.Configuration.AddJsonFile($"{configurationsDirectory}/AuthSettings.json", optional: true, reloadOnChange: false);
builder.Host.UseSerilog((context, configuration) =>
{
configuration
.WriteTo.Console().ReadFrom.Configuration(context.Configuration)
.WriteTo.Logger(x =>
{
x.WriteTo.File(new CsvFormatter(),
path: "./Logs/HeadClerkLog-.csv",
hooks: new HeaderWriter("Date,ChassisId,ShopId,Baid,PlayedAt,IsRight,Type,Amount"),
rollingInterval: RollingInterval.Day);
x.Filter.ByIncludingOnly("StartsWith(@m, 'CSV WRITE:')");
});
});
if (builder.Configuration.GetValue<bool>("ServerSettings:EnableMoreSongs"))
{
Log.Warning("Song limit expanded! Use at your own risk!");
}
// Add response compression services
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<BrotliCompressionProvider>();
});
builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
// Add services to the container.
builder.Services.AddOptions();
builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddAdminApi(builder.Configuration);
builder.Services.AddAllnetMucha();
builder.Services.AddGameProtocolWwR08();
builder.Services.AddGameProtocolCnR00();
builder.Services.AddControllers().AddProtoBufNet();
builder.Services.AddMemoryCache();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAllCorsPolicy", policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddSingleton<SongBestResponseMapper>();
var app = builder.Build();
// Migrate db
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<TaikoDbContext>();
db.Database.Migrate();
}
app.UseSerilogRequestLogging(options =>
{
options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms, " +
"request host: {RequestHost}";
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
};
});
var gameDataCatalog = app.Services.GetService<IGameDataCatalog>();
gameDataCatalog.ThrowIfNull();
await gameDataCatalog.InitializeAsync();
// Use response compression
app.UseResponseCompression();
// For reverse proxy
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseCors("AllowAllCorsPolicy");
// For blazor hosting
if (app.Environment.IsDevelopment())
{
// The Blazor WASM boot manifest under /_framework is not content-hashed,
// so a cached one will pin mismatched assembly versions across rebuilds.
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/_framework"))
{
context.Response.Headers.CacheControl = "no-store, no-cache, must-revalidate";
context.Response.Headers.Pragma = "no-cache";
}
await next();
});
}
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
// Enable Authentication and Authorization middleware
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpLogging();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == StatusCodes.Status404NotFound)
{
Log.Error("Unknown request from: {RemoteIpAddress} {Method} {Path} {StatusCode}",
context.Connection.RemoteIpAddress, context.Request.Method, context.Request.Path, context.Response.StatusCode);
Log.Error("Request headers: {Headers}", context.Request.Headers);
}
else if (context.Response.StatusCode >= StatusCodes.Status400BadRequest
&& context.Response.StatusCode != StatusCodes.Status401Unauthorized)
{
Log.Warning("Unsuccessful request from: {RemoteIpAddress} {Method} {Path} {StatusCode}",
context.Connection.RemoteIpAddress, context.Request.Method, context.Request.Path, context.Response.StatusCode);
Log.Warning("Request headers: {Headers}", context.Request.Headers);
}
});
app.MapControllers();
app.MapFallbackToFile("index.html");
app.UseAllnetMucha();
app.Run();
}
catch (Exception ex) when (ex.GetType().Name is not "HostAbortedException")
{
Log.Fatal(ex, "Unhandled exception");
}
finally
{
Log.Information("Shut down complete");
Log.CloseAndFlush();
}