Initial commit: Add project files
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../KArtSell.BuildingBlocks/KArtSell.BuildingBlocks.csproj" />
|
||||
<ProjectReference Include="../KArtSell.Modules.SignalEngine/KArtSell.Modules.SignalEngine.csproj" />
|
||||
<ProjectReference Include="../KArtSell.Modules.ModelOperations/KArtSell.Modules.ModelOperations.csproj" />
|
||||
<PackageReference Include="FastEndpoints" />
|
||||
<PackageReference Include="Hangfire.AspNetCore" />
|
||||
<PackageReference Include="Hangfire.PostgreSql" />
|
||||
<PackageReference Include="Npgsql" />
|
||||
<PackageReference Include="Polly" />
|
||||
<PackageReference Include="Serilog.AspNetCore" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" />
|
||||
<PackageReference Include="OpenTelemetry.Extensions.Hosting" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.Http" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,147 @@
|
||||
using FastEndpoints;
|
||||
using Hangfire;
|
||||
using Hangfire.PostgreSql;
|
||||
using KArtSell.BuildingBlocks.Capabilities;
|
||||
using KArtSell.BuildingBlocks.Data;
|
||||
using KArtSell.BuildingBlocks.Reliability;
|
||||
using KArtSell.BuildingBlocks.Time;
|
||||
using KArtSell.Host.Security;
|
||||
using KArtSell.Modules.ModelOperations;
|
||||
using KArtSell.Modules.ModelOperations.Scheduling;
|
||||
using KArtSell.Modules.SignalEngine;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Npgsql;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
using Serilog;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Host.UseSerilog((context, services, logger) => logger
|
||||
.ReadFrom.Configuration(context.Configuration)
|
||||
.ReadFrom.Services(services)
|
||||
.Enrich.FromLogContext()
|
||||
.WriteTo.Console());
|
||||
|
||||
var connectionString = builder.Configuration.GetConnectionString("Postgres")
|
||||
?? throw new InvalidOperationException("ConnectionStrings:Postgres is required.");
|
||||
|
||||
var modelOperationsDispatcherEnabled = builder.Configuration.GetValue<bool>("ModelOperations:DispatcherEnabled");
|
||||
var modelOperationsDispatcherCron = builder.Configuration["ModelOperations:DispatcherCron"] ?? "*/15 * * * *";
|
||||
|
||||
builder.Services.AddOptions<CapabilityOptions>()
|
||||
.Bind(builder.Configuration.GetSection(CapabilityOptions.SectionName))
|
||||
.Validate(x => !x.AutomaticOrder, "AutomaticOrder must remain OFF in this package.")
|
||||
.Validate(x => !x.KisOrderAdapter, "KisOrderAdapter must remain OFF until a separately approved release.")
|
||||
.Validate(x => !modelOperationsDispatcherEnabled || x.ShadowEvaluation,
|
||||
"ModelOperations dispatcher requires ShadowEvaluation capability and remains evidence-only.")
|
||||
.ValidateOnStart();
|
||||
|
||||
var dataSource = new NpgsqlDataSourceBuilder(connectionString).Build();
|
||||
builder.Services.AddSingleton(dataSource);
|
||||
builder.Services.AddSingleton<IDbConnectionFactory, NpgsqlConnectionFactory>();
|
||||
builder.Services.AddSingleton<IOutboxWriter, DapperOutboxWriter>();
|
||||
builder.Services.AddSingleton<IInboxStore, DapperInboxStore>();
|
||||
builder.Services.AddSingleton<IJobRunRepository, DapperJobRunRepository>();
|
||||
builder.Services.AddSingleton<IClock, SystemClock>();
|
||||
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddFastEndpoints();
|
||||
|
||||
const string authenticationScheme = "KArtSell";
|
||||
var authenticationMode = builder.Configuration["Authentication:Mode"] ?? "FailClosed";
|
||||
var authenticationBuilder = builder.Services
|
||||
.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = authenticationScheme;
|
||||
options.DefaultChallengeScheme = authenticationScheme;
|
||||
});
|
||||
|
||||
if (builder.Environment.IsDevelopment()
|
||||
&& authenticationMode.Equals("DevelopmentHeader", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
authenticationBuilder.AddScheme<AuthenticationSchemeOptions, DevelopmentHeaderAuthenticationHandler>(
|
||||
authenticationScheme,
|
||||
_ => { });
|
||||
}
|
||||
else
|
||||
{
|
||||
authenticationBuilder.AddScheme<AuthenticationSchemeOptions, FailClosedAuthenticationHandler>(
|
||||
authenticationScheme,
|
||||
_ => { });
|
||||
}
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddSignalEngineModule();
|
||||
builder.Services.AddModelOperationsModule();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddHangfire(config => config.UsePostgreSqlStorage(options =>
|
||||
options.UseNpgsqlConnection(connectionString)));
|
||||
builder.Services.AddHangfireServer(options =>
|
||||
{
|
||||
options.Queues =
|
||||
[
|
||||
"q-control",
|
||||
"q-market-data",
|
||||
"q-fundamentals",
|
||||
"q-feature-risk",
|
||||
"q-recommendation",
|
||||
"q-evaluation",
|
||||
"q-reconciliation",
|
||||
"q-research",
|
||||
"q-backfill"
|
||||
];
|
||||
options.WorkerCount = Math.Max(2, Environment.ProcessorCount / 2);
|
||||
});
|
||||
|
||||
builder.Services.AddOpenTelemetry()
|
||||
.ConfigureResource(resource => resource.AddService("KArtSell.Host"))
|
||||
.WithTracing(tracing => tracing
|
||||
.AddAspNetCoreInstrumentation()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddOtlpExporter())
|
||||
.WithMetrics(metrics => metrics
|
||||
.AddAspNetCoreInstrumentation()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddRuntimeInstrumentation()
|
||||
.AddOtlpExporter());
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseExceptionHandler();
|
||||
app.UseStatusCodePages();
|
||||
app.UseSerilogRequestLogging();
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseFastEndpoints(config => config.Endpoints.RoutePrefix = "api");
|
||||
|
||||
app.Services.RegisterModelOperationsSchedules(modelOperationsDispatcherEnabled, modelOperationsDispatcherCron);
|
||||
|
||||
app.MapGet("/health/live", () => Results.Ok(new
|
||||
{
|
||||
status = "ok",
|
||||
automaticOrderCapability = "OFF",
|
||||
algorithmStatus = "RESEARCH_CANDIDATE_NOT_PRODUCTION"
|
||||
}));
|
||||
|
||||
app.MapGet("/health/ready", async (NpgsqlDataSource source, CancellationToken ct) =>
|
||||
{
|
||||
await using var connection = await source.OpenConnectionAsync(ct);
|
||||
await using var command = connection.CreateCommand();
|
||||
command.CommandText = "select 1";
|
||||
await command.ExecuteScalarAsync(ct);
|
||||
return Results.Ok(new { status = "ready", database = "reachable" });
|
||||
});
|
||||
|
||||
app.Run();
|
||||
|
||||
public partial class Program;
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace KArtSell.Host.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Development-only authentication. Never enable outside Development.
|
||||
/// Required headers: X-KArtSell-User and X-KArtSell-Role.
|
||||
/// </summary>
|
||||
public sealed class DevelopmentHeaderAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
IWebHostEnvironment environment)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (!environment.IsDevelopment())
|
||||
{
|
||||
return Task.FromResult(AuthenticateResult.Fail(
|
||||
"Development header authentication is disabled outside Development."));
|
||||
}
|
||||
|
||||
var user = Request.Headers["X-KArtSell-User"].ToString();
|
||||
var role = Request.Headers["X-KArtSell-Role"].ToString();
|
||||
if (string.IsNullOrWhiteSpace(user) || string.IsNullOrWhiteSpace(role))
|
||||
{
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
}
|
||||
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, user),
|
||||
new Claim(ClaimTypes.Name, user),
|
||||
new Claim(ClaimTypes.Role, role),
|
||||
new Claim("auth_mode", "development_header")
|
||||
};
|
||||
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
return Task.FromResult(AuthenticateResult.Success(
|
||||
new AuthenticationTicket(principal, Scheme.Name)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace KArtSell.Host.Security;
|
||||
|
||||
public sealed class FailClosedAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
=> Task.FromResult(AuthenticateResult.Fail(
|
||||
"Authentication provider is not configured. The service is fail-closed."));
|
||||
|
||||
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Authentication": {
|
||||
"Mode": "DevelopmentHeader"
|
||||
},
|
||||
"ModelOperations": {
|
||||
"DispatcherEnabled": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"Postgres": "Host=localhost;Port=5432;Database=kartsell;Username=kartsell;Password=kartsell"
|
||||
},
|
||||
"Authentication": {
|
||||
"Mode": "FailClosed"
|
||||
},
|
||||
"Capabilities": {
|
||||
"AutomaticOrder": false,
|
||||
"KisOrderAdapter": false,
|
||||
"ClientPublication": false,
|
||||
"ShadowEvaluation": true
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
},
|
||||
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4317",
|
||||
"ModelOperations": {
|
||||
"DispatcherEnabled": false,
|
||||
"DispatcherCron": "*/15 * * * *",
|
||||
"Boundary": "EVIDENCE_ONLY_NO_AUTO_MODEL_OR_ORDER_MUTATION"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user