Correctness/data: - Fix demo cost double-count: reference importer no longer imports the Kosten Strom/Wasser columns for categories that are metered (only Heizung), so Wasser rollup is 70€ not 140€. - Spurious-decrease guard: only a reset/swap in the window (prevReading, thisReading] explains a decrease — an old historical reset no longer permanently disables the guard. - Gate swap auto-detection on MappingProfile.DetectCumulativeSwaps (flag was ignored). - Prorate basePrice by bucket length (day/month/year); guard virtual expressions against NaN/Inf. Concurrency/infra: - Blazor: register a DbContextFactory; CostService/DashboardService and the read pages now use short-lived per-operation contexts (no shared circuit DbContext); guard Trends re-entrancy. - /events: wrap event insert + consumption recompute in one transaction (atomic); 404 (not 500) on unknown meter. - MQTT worker: subscribe to newly-added topics on each tick; move client cleanup into finally. - Migrations: CREATE MATERIALIZED VIEW IF NOT EXISTS + if_not_exists on CAgg/compression/ hypertable calls (re-run-safe after a mid-migration crash). - HA worker: prune stale poll-schedule entries; export: null dangling ImportBatchIds on restore. API/security: - API fail-closed by default: with no keys and AllowAnonymousApi off, /api/v1 returns 401 (protects /export and /import). New MeterVault:AllowAnonymousApi opt-in. - Cap /readings batch at 5000; report ignored (unknown-meter) count; enums as strings in JSON. +4 regression tests (guard window, API closed, /events 404, no demo double-count). 98 tests green; Docker deploy re-verified healthy with the API fail-closed. Claude-Session: https://claude.ai/code/session_01WujdMtMJPbxDpDnMeK22rr
This commit is contained in:
@@ -17,18 +17,25 @@ public sealed record EventPush(int MeterId, DateTimeOffset Time, MeterEventType
|
||||
public sealed record TariffPush(TariffScope ScopeType, int? ScopeId, TariffComponent Component,
|
||||
double Value, string Unit, DateOnly ValidFrom, DateOnly? ValidTo);
|
||||
|
||||
public sealed record IngestResult(int Written, int Updated, int Rejected);
|
||||
public sealed record IngestResult(int Written, int Updated, int Rejected, int Ignored);
|
||||
|
||||
/// <summary>Maps the versioned REST API. All endpoints require a valid API key (SDD §9).</summary>
|
||||
public static class ApiEndpoints
|
||||
{
|
||||
private const int MaxReadingsPerRequest = 5000;
|
||||
|
||||
public static IEndpointRouteBuilder MapMeterVaultApi(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var api = app.MapGroup("/api/v1").AddEndpointFilter<ApiKeyFilter>().WithTags("MeterVault");
|
||||
|
||||
api.MapPost("/readings", async (ReadingPush[] readings, IngestionService ingestion, CancellationToken ct) =>
|
||||
{
|
||||
int written = 0, updated = 0, rejected = 0;
|
||||
if (readings.Length > MaxReadingsPerRequest)
|
||||
{
|
||||
return Results.BadRequest(new { error = $"At most {MaxReadingsPerRequest} readings per request." });
|
||||
}
|
||||
|
||||
int written = 0, updated = 0, rejected = 0, ignored = 0;
|
||||
foreach (var r in readings)
|
||||
{
|
||||
switch (await ingestion.IngestByMeterAsync(r.MeterId, r.Time, r.Value, ct))
|
||||
@@ -36,11 +43,11 @@ public static class ApiEndpoints
|
||||
case IngestionOutcome.Written: written++; break;
|
||||
case IngestionOutcome.Updated: updated++; break;
|
||||
case IngestionOutcome.RejectedDecrease: rejected++; break;
|
||||
default: break;
|
||||
default: ignored++; break; // unknown meter
|
||||
}
|
||||
}
|
||||
|
||||
return Results.Ok(new IngestResult(written, updated, rejected));
|
||||
return Results.Ok(new IngestResult(written, updated, rejected, ignored));
|
||||
}).WithSummary("Ingest one or more readings (idempotent). Lets Home Assistant push.");
|
||||
|
||||
api.MapGet("/meters", async (MeterVaultDbContext db, CancellationToken ct) =>
|
||||
@@ -70,6 +77,14 @@ public static class ApiEndpoints
|
||||
api.MapPost("/events", async (EventPush push, MeterVaultDbContext db,
|
||||
NormalizationService normalization, CancellationToken ct) =>
|
||||
{
|
||||
if (!await db.Meters.AnyAsync(m => m.Id == push.MeterId, ct))
|
||||
{
|
||||
return Results.NotFound(new { error = $"Meter {push.MeterId} does not exist." });
|
||||
}
|
||||
|
||||
// One transaction so the event insert + consumption recompute (which deletes then
|
||||
// re-inserts) are atomic — a failure must not leave the meter with no consumption.
|
||||
await using var tx = await db.Database.BeginTransactionAsync(ct);
|
||||
db.MeterEvents.Add(new MeterEvent
|
||||
{
|
||||
MeterId = push.MeterId,
|
||||
@@ -84,6 +99,7 @@ public static class ApiEndpoints
|
||||
await db.SaveChangesAsync(ct);
|
||||
await normalization.RecomputeMeterAsync(push.MeterId, null, ct);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await tx.CommitAsync(ct);
|
||||
return Results.Ok();
|
||||
}).WithSummary("Record a delivery / swap / tank level / correction and recompute the meter.");
|
||||
|
||||
|
||||
@@ -17,7 +17,11 @@ public sealed class ApiKeyFilter(IOptions<MeterVaultOptions> options) : IEndpoin
|
||||
{
|
||||
if (_options.ApiKeys.Count == 0)
|
||||
{
|
||||
return await next(context).ConfigureAwait(false);
|
||||
// Fail closed: an unconfigured deployment must not expose export/import. Opt in explicitly.
|
||||
return _options.AllowAnonymousApi
|
||||
? await next(context).ConfigureAwait(false)
|
||||
: Results.Problem(statusCode: StatusCodes.Status401Unauthorized,
|
||||
title: "API is closed: configure MeterVault:ApiKeys or set AllowAnonymousApi=true.");
|
||||
}
|
||||
|
||||
var provided = context.HttpContext.Request.Headers[HeaderName].ToString();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
@page "/admin/energy-types"
|
||||
@rendermode InteractiveServer
|
||||
@inject MeterVault.Infrastructure.Persistence.MeterVaultDbContext Db
|
||||
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<MeterVault.Infrastructure.Persistence.MeterVaultDbContext> DbFactory
|
||||
@using Microsoft.EntityFrameworkCore
|
||||
|
||||
<PageTitle>MeterVault — Energy types</PageTitle>
|
||||
@@ -32,6 +32,9 @@ else
|
||||
@code {
|
||||
private List<EnergyType>? _types;
|
||||
|
||||
protected override async Task OnInitializedAsync() =>
|
||||
_types = await Db.EnergyTypes.AsNoTracking().OrderBy(t => t.Id).ToListAsync();
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await using var db = await DbFactory.CreateDbContextAsync();
|
||||
_types = await db.EnergyTypes.AsNoTracking().OrderBy(t => t.Id).ToListAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
@page "/admin/tariffs"
|
||||
@rendermode InteractiveServer
|
||||
@inject MeterVault.Infrastructure.Persistence.MeterVaultDbContext Db
|
||||
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<MeterVault.Infrastructure.Persistence.MeterVaultDbContext> DbFactory
|
||||
@using Microsoft.EntityFrameworkCore
|
||||
|
||||
<PageTitle>MeterVault — Tariffs</PageTitle>
|
||||
@@ -40,8 +40,11 @@ else
|
||||
@code {
|
||||
private List<Tariff>? _tariffs;
|
||||
|
||||
protected override async Task OnInitializedAsync() =>
|
||||
_tariffs = await Db.Tariffs.AsNoTracking()
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await using var db = await DbFactory.CreateDbContextAsync();
|
||||
_tariffs = await db.Tariffs.AsNoTracking()
|
||||
.OrderBy(t => t.Component).ThenBy(t => t.ValidFrom)
|
||||
.ToListAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
@page "/meters"
|
||||
@rendermode InteractiveServer
|
||||
@inject MeterVault.Infrastructure.Persistence.MeterVaultDbContext Db
|
||||
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<MeterVault.Infrastructure.Persistence.MeterVaultDbContext> DbFactory
|
||||
@using Microsoft.EntityFrameworkCore
|
||||
|
||||
<PageTitle>MeterVault — Meters</PageTitle>
|
||||
@@ -54,7 +54,8 @@ else
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_meters = await Db.Meters
|
||||
await using var db = await DbFactory.CreateDbContextAsync();
|
||||
_meters = await db.Meters
|
||||
.AsNoTracking()
|
||||
.Include(m => m.EnergyType)
|
||||
.Include(m => m.Sources)
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<MudSelectItem T="int" Value="24">Last 24 months</MudSelectItem>
|
||||
<MudSelectItem T="int" Value="48">Last 48 months</MudSelectItem>
|
||||
</MudSelect>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="LoadAsync">Apply</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="LoadAsync" Disabled="_loading">Apply</MudButton>
|
||||
</div>
|
||||
|
||||
@if (_loading)
|
||||
@@ -38,10 +38,21 @@
|
||||
|
||||
private async Task LoadAsync()
|
||||
{
|
||||
if (_loading)
|
||||
{
|
||||
return; // guard against overlapping loads
|
||||
}
|
||||
|
||||
_loading = true;
|
||||
var asOf = DateOnly.FromDateTime(DateTime.UtcNow);
|
||||
var from = asOf.AddMonths(-_months);
|
||||
_points = await Dash.GetMonthlyTrendAsync(new DateOnly(from.Year, from.Month, 1), asOf.AddMonths(1));
|
||||
_loading = false;
|
||||
try
|
||||
{
|
||||
var asOf = DateOnly.FromDateTime(DateTime.UtcNow);
|
||||
var from = asOf.AddMonths(-_months);
|
||||
_points = await Dash.GetMonthlyTrendAsync(new DateOnly(from.Year, from.Month, 1), asOf.AddMonths(1));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_loading = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,10 @@ try
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
// Serialize/accept enums as strings on the REST API (e.g. event Type "Delivery").
|
||||
builder.Services.ConfigureHttpJsonOptions(o =>
|
||||
o.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()));
|
||||
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
c.SwaggerDoc("v1", new() { Title = "MeterVault API", Version = "v1" }));
|
||||
|
||||
Reference in New Issue
Block a user