Files
Khaemhat/src/Khaemhat.Application/Configuration/EnvironmentConfigurationReader.cs
T
Alby96andClaude Opus 5.5 f415dc37a8 feat: in-app help, notifications panel and global search (#32)
F1 and "?" now open the wiki page of the screen inside the application
(/aiuto, mockup 011) from a copy of the wiki shipped next to the program,
so help works offline and always matches the installed version. Markdown
is converted in-house and fully encoded; images of the repository are
served from the copy. KHAEMHAT_HELP_URL sets the online wiki behind
"Apri nel wiki"; "Segnala un problema" opens a new issue of that repo.
A test checks that every page and menu entry has an existing wiki page.

The bell opens a notifications panel (mockup 010) with all/unread
filters and mark read. Broadcast notifications are now read per user
through sys_notification_reads / notification_reads instead of one
shared read_at.

The global search asks ISearchProvider implementations through
GlobalSearchService after a short pause; the first provider finds help
pages and sections, # and @ say which modules will fill them.

Escape also closes a side panel when the focus fell out of it.
Decisions in ADR 0023.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:39:17 +01:00

117 lines
4.8 KiB
C#

namespace Khaemhat.Application.Configuration;
/// <summary>
/// Reads the <c>KHAEMHAT_*</c> variables of SPEC §6 into <see cref="KhaemhatOptions"/>, applying the <c>_FILE</c>
/// rule of ADR 0014 to the sensitive ones: when <c>X_FILE</c> is set, the value of <c>X</c> is the content of that file
/// without the final line break; setting both is a configuration error, and so is a file that cannot be read.
/// Problems are collected in <see cref="KhaemhatOptions.ReadErrors"/>; values never appear in messages.
/// </summary>
public sealed class EnvironmentConfigurationReader
{
/// <summary>The variables that accept a <c>_FILE</c> variant (ADR 0014).</summary>
public static readonly IReadOnlySet<string> FileVariables = new HashSet<string>(StringComparer.Ordinal)
{
"KHAEMHAT_SYSTEM_DB", "KHAEMHAT_DB_SERVER", "KHAEMHAT_SECRET_KEY", "KHAEMHAT_SECRET_KEY_NEW",
"KHAEMHAT_SUPERUSER", "KHAEMHAT_SUPERUSER_PASSWORD", "KHAEMHAT_SUPERUSER_EMAIL", "KHAEMHAT_LICENSE",
"KHAEMHAT_REDIS", "KHAEMHAT_SMTP_PASSWORD", "KHAEMHAT_UPDATE_TOKEN",
};
private readonly Func<string, string?> _lookup;
private readonly Func<string, string> _readFile;
/// <summary>Creates a reader.</summary>
/// <param name="lookup">Returns a variable, or <see langword="null"/> when unset (the host configuration: environment and command line).</param>
/// <param name="readFile">Reads a secret file; the default reads from disk.</param>
public EnvironmentConfigurationReader(Func<string, string?> lookup, Func<string, string>? readFile = null)
{
ArgumentNullException.ThrowIfNull(lookup);
_lookup = lookup;
_readFile = readFile ?? File.ReadAllText;
}
/// <summary>Reads every variable.</summary>
/// <returns>The options, with the reading problems in <see cref="KhaemhatOptions.ReadErrors"/>.</returns>
public KhaemhatOptions Read()
{
var errors = new List<string>();
string? Get(string name) => Value(name, errors);
return new KhaemhatOptions
{
SystemDb = Get("KHAEMHAT_SYSTEM_DB"),
DbServer = Get("KHAEMHAT_DB_SERVER"),
SecretKey = Get("KHAEMHAT_SECRET_KEY"),
RotationSecretKey = Get("KHAEMHAT_SECRET_KEY_NEW"),
SuperUser = Get("KHAEMHAT_SUPERUSER"),
SuperUserPassword = Get("KHAEMHAT_SUPERUSER_PASSWORD"),
SuperUserEmail = Get("KHAEMHAT_SUPERUSER_EMAIL"),
CompanyCode = Get("KHAEMHAT_COMPANY_CODE"),
CompanyName = Get("KHAEMHAT_COMPANY_NAME"),
Country = Get("KHAEMHAT_COUNTRY") ?? "IT",
LicenseMode = Get("KHAEMHAT_LICENSE_MODE") ?? "production",
License = Get("KHAEMHAT_LICENSE"),
Redis = Get("KHAEMHAT_REDIS"),
DataDir = Get("KHAEMHAT_DATA_DIR") ?? "/data",
Urls = Get("KHAEMHAT_URLS"),
PublicUrl = Get("KHAEMHAT_PUBLIC_URL"),
SmtpHost = Get("KHAEMHAT_SMTP_HOST"),
SmtpPort = Get("KHAEMHAT_SMTP_PORT"),
SmtpUser = Get("KHAEMHAT_SMTP_USER"),
SmtpPassword = Get("KHAEMHAT_SMTP_PASSWORD"),
SmtpFrom = Get("KHAEMHAT_SMTP_FROM"),
SmtpSecurity = Get("KHAEMHAT_SMTP_SECURITY"),
LogLevel = Get("KHAEMHAT_LOG_LEVEL"),
SeedBase = Get("KHAEMHAT_SEED_BASE"),
SeedDemo = Get("KHAEMHAT_SEED_DEMO"),
UpdateFeed = Get("KHAEMHAT_UPDATE_FEED"),
UpdateToken = Get("KHAEMHAT_UPDATE_TOKEN"),
HelpUrl = Get("KHAEMHAT_HELP_URL"),
TimeZone = Get("TZ"),
ReadErrors = errors,
};
}
private string? Value(string name, List<string> errors)
{
var direct = Normalize(_lookup(name));
if (!FileVariables.Contains(name))
{
return direct;
}
var path = Normalize(_lookup(name + "_FILE"));
if (path is null)
{
return direct;
}
if (direct is not null)
{
errors.Add($"{name} and {name}_FILE are both set: keep only one of them.");
return null;
}
try
{
return Normalize(TrimFinalLineBreak(_readFile(path)));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
errors.Add($"{name}_FILE points to a file that cannot be read ({ex.GetType().Name}): check the path and the permissions of the secret.");
return null;
}
}
private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value;
private static string TrimFinalLineBreak(string value)
{
if (value.EndsWith("\r\n", StringComparison.Ordinal))
{
return value[..^2];
}
return value.EndsWith('\n') ? value[..^1] : value;
}
}