ci / build-test (push) Failing after 35s
The last open item on the M7 list. Number and currency formatting was already locale-aware, but every string in the UI was an English literal, so a German instance read half in each language -- German data, English chrome. This translates all of it and adds the machinery to keep it translated. Strings live in Localization/Strings.resx (English, neutral) and Strings.de.resx. The neutral file generates a strongly-typed accessor at build time, aliased as S in _Imports.razor, so components reference compiled properties -- @S.Common_Save, not a string key. That choice is the point: across 4,500 lines of markup, a key lookup that silently falls back to its own name is a defect you find in production, while a renamed property is a build error. Generation runs in MSBuild rather than the IDE designer, so dotnet build alone reproduces it anywhere. Resource fallback is the hazard here. Ask for a key the German satellite lacks and ResourceManager quietly serves the English one -- correct at runtime, disastrous at release time, because a half-translated build looks perfectly healthy. StringResourceTests reads each satellite with tryParents: false, which is the only way to see what one actually contains, and fails on a missing or blank translation, a placeholder that changed arity, an orphan, or a key nothing references. Three things needed more than substitution: - Domain enums reached the screen as bare identifiers. They stay bare in the model -- they are persisted as text and appear in the REST API, so their names are part of the data contract -- and DisplayNames is now the single place that decides how each value is spoken. Every arm ends in a fallback returning the identifier, so a value added later cannot throw mid-render; EnumDisplayNameTests is what stops that safety net quietly becoming the shipping behaviour. - Infrastructure was writing display text: FlowService's "Other (X)", MeterPeriodView's "Generation"/"Consumption", the HA connection-test verdicts, the updater's snackbar, the CSV importer's row warnings. Each now returns an outcome value and the UI supplies the words, which is where the reader's language is known. Diagnostics that are not ours -- an HTTP status, systemd's stderr, an exception message -- are passed through untranslated, and every English summary is kept alongside the outcome so log lines never move with the UI language. The UpdateRunner change is additive only; no gate was touched. - Importer warnings carry their arguments rather than a finished sentence, so the numbers inside them pick up the reader's grouping. A register that reads 2.940,19 everywhere else must not read 2940.19 only inside a warning. Switching language is a redirect through /culture/set followed by a full reload, not an interactive state change: a Blazor Server circuit is fixed to the culture of the request that opened it. That makes the endpoint a redirector taking its target from the query string, so anything but a local path is refused rather than followed. Preference order is the cookie, then Accept-Language, then MeterVault__Locale -- an instance can be pinned to one language and a reader can still switch. Locale keeps its documented default of "en". Format now follows CurrentCulture instead of a hardcoded de-DE, so an instance with nothing configured and a browser asking for English will show English number formatting where it previously showed German; set MeterVault__Locale=de to pin the old behaviour. The importer's de-DE parsing is untouched and stays that way -- that dialect is a property of the spreadsheets, not of whoever is looking at the dashboard. Anything that comes from the database -- meter names, energy-type display names, category names -- is user data and is never translated. Claude-Session: https://claude.ai/code/session_0112ezeWqaZ85kTj5bYu9JHx
120 lines
5.4 KiB
C#
120 lines
5.4 KiB
C#
using System.Net.Http.Headers;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace MeterVault.Infrastructure.Ingestion;
|
|
|
|
/// <summary>Which way a Home Assistant connectivity test ended.</summary>
|
|
/// <remarks>
|
|
/// The verdict is shown to whoever clicked "Test connection", so it has to be sayable in their
|
|
/// language — and this assembly has no business knowing what that is. The outcome travels as a
|
|
/// value and the admin UI supplies the words.
|
|
/// </remarks>
|
|
public enum HaTestOutcome
|
|
{
|
|
/// <summary>
|
|
/// No test was run — the caller decided beforehand (no token configured, base URL edited since
|
|
/// saving) and put its own, already-localized wording in <see cref="HaTestResult.Message"/>.
|
|
/// The default, so a result built by the UI needs no ceremony to say so.
|
|
/// </summary>
|
|
Precondition,
|
|
|
|
/// <summary>Reachable and the token was accepted; no entity was named to sample.</summary>
|
|
Connected,
|
|
|
|
/// <summary>Reachable and the named entity returned a number — see <see cref="HaTestResult.SampleValue"/>.</summary>
|
|
ConnectedWithValue,
|
|
|
|
/// <summary>No base URL was given.</summary>
|
|
BaseUrlMissing,
|
|
|
|
/// <summary>No token was available to test with.</summary>
|
|
TokenMissing,
|
|
|
|
/// <summary>HA answered, but not with success. <see cref="HaTestResult.Detail"/> carries the status.</summary>
|
|
HttpError,
|
|
|
|
/// <summary>Reachable, but the named entity has no numeric state (unavailable/unknown/non-numeric).</summary>
|
|
NoNumericState,
|
|
|
|
/// <summary>The request threw. <see cref="HaTestResult.Detail"/> carries the exception message.</summary>
|
|
RequestFailed,
|
|
}
|
|
|
|
/// <summary>Outcome of a Home Assistant connectivity test.</summary>
|
|
/// <param name="Message">The English summary, kept for logs and non-UI callers.</param>
|
|
/// <param name="Outcome">The same verdict as a value, for a UI that has to phrase it in some language.</param>
|
|
/// <param name="EntityId">The entity that was sampled, when one was named.</param>
|
|
/// <param name="Detail">Diagnostic text (HTTP status, exception message). Not ours to translate.</param>
|
|
public sealed record HaTestResult(
|
|
bool Ok,
|
|
string Message,
|
|
double? SampleValue = null,
|
|
HaTestOutcome Outcome = HaTestOutcome.Precondition,
|
|
string? EntityId = null,
|
|
string? Detail = null);
|
|
|
|
/// <summary>
|
|
/// Verifies a Home Assistant connection from the admin UI: checks the base URL + token against
|
|
/// <c>GET /api/</c>, and optionally reads one entity's state. Confirms the app can actually read HA
|
|
/// before a source is relied upon (SDD §6.2).
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Takes the token already resolved rather than a reference to one. The admin UI must be able to
|
|
/// test a token that has been typed but not yet saved (so not yet encrypted), and keeping the two
|
|
/// storage forms out of here leaves one resolution path in <see cref="EndpointSecret"/>.
|
|
/// </remarks>
|
|
public sealed class HaConnectionTester(IHttpClientFactory httpClientFactory, ILogger<HaConnectionTester> logger)
|
|
{
|
|
private readonly IHttpClientFactory _httpClientFactory = httpClientFactory;
|
|
private readonly ILogger<HaConnectionTester> _logger = logger;
|
|
|
|
public async Task<HaTestResult> TestAsync(
|
|
string? baseUrl, string? token, string? entityId, CancellationToken cancellationToken = default)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(baseUrl))
|
|
{
|
|
return new HaTestResult(false, "Base URL is required.", Outcome: HaTestOutcome.BaseUrlMissing);
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(token))
|
|
{
|
|
return new HaTestResult(false, "No token available to test.", Outcome: HaTestOutcome.TokenMissing);
|
|
}
|
|
|
|
var client = _httpClientFactory.CreateClient();
|
|
client.Timeout = TimeSpan.FromSeconds(10);
|
|
|
|
try
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, $"{baseUrl.TrimEnd('/')}/api/");
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
|
using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
return new HaTestResult(false, $"HA returned {(int)response.StatusCode} {response.ReasonPhrase}.",
|
|
Outcome: HaTestOutcome.HttpError,
|
|
Detail: $"{(int)response.StatusCode} {response.ReasonPhrase}".Trim());
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(entityId))
|
|
{
|
|
return new HaTestResult(true, "Connected — Home Assistant API reachable and token accepted.",
|
|
Outcome: HaTestOutcome.Connected);
|
|
}
|
|
|
|
var state = await new HaStateClient(client).GetStateAsync(baseUrl, token, entityId, null, cancellationToken).ConfigureAwait(false);
|
|
return state is { } value
|
|
? new HaTestResult(true, $"Connected — {entityId} = {value.Value}.", value.Value,
|
|
HaTestOutcome.ConnectedWithValue, entityId)
|
|
: new HaTestResult(false, $"Connected, but '{entityId}' has no numeric state (unavailable/unknown or non-numeric).",
|
|
Outcome: HaTestOutcome.NoNumericState, EntityId: entityId);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Home Assistant connection test failed for {BaseUrl}", baseUrl);
|
|
return new HaTestResult(false, $"Connection failed: {ex.Message}",
|
|
Outcome: HaTestOutcome.RequestFailed, Detail: ex.Message);
|
|
}
|
|
}
|
|
}
|