using Microsoft.Extensions.Configuration;
namespace ZB.MOM.WW.OtOpcUa.Cluster;
/// Which of the two role sources resolved from.
public enum RoleSource
{
/// Neither source named any role.
None,
/// Cluster:Roles was non-empty and won outright.
Configured,
/// Cluster:Roles was empty; OTOPCUA_ROLES supplied the roles.
Environment,
}
/// The node's effective cluster roles — the SINGLE authority for "what is this node".
/// Resolved once, from one documented precedence, and consumed by BOTH the Host's conditional
/// wiring and the Akka role list, so the two cannot disagree (archreview 01/S-12 = 03/C5).
///
/// Precedence: Cluster:Roles when non-empty, else OTOPCUA_ROLES,
/// else empty. Unchanged from
/// — what changed is that Program.cs now obeys it too, instead of reading the environment
/// directly.
/// Normalization is two-layer, on purpose. lower-cases plain
/// roles (Akka matches gossiped role names ORDINALLY, and every consumer compares against a
/// lowercase constant) but keeps a cluster role's ClusterId suffix VERBATIM — lower-casing that
/// would rename cluster-SITE-A on a running fleet, and a rolling pair upgrade would gossip
/// two different role names mid-window. Lower-casing a plain role changes the wire only for a
/// node that is already broken (archreview 01/S-12 = 03/C5, 01/C-9).
/// Validation runs on BOTH sources. The environment path was always validated by
/// ; the configured path previously accepted anything verbatim
/// (Cluster:Roles: ["Drivr"] silently gossiped a role that matched nothing). Both now fail
/// fast, naming the offending key, on an unknown role — a miscased but KNOWN role still
/// normalizes silently rather than failing, or an operator's Driver would brick the node
/// at the exact moment they upgrade.
///
public sealed class EffectiveRoles
{
private EffectiveRoles(IReadOnlyList gossiped, RoleSource source, string? disagreementWarning)
{
Gossiped = gossiped;
Source = source;
DisagreementWarning = disagreementWarning;
ClusterRole = RoleParser.ClusterRoleFromRoles(gossiped);
ClusterId = ClusterRole is null ? null : RoleParser.ClusterIdFromRole(ClusterRole);
}
/// The configuration key reads for the configured
/// side of the precedence.
public const string ConfiguredRolesKey = "Cluster:Roles";
/// The roles as they are handed to Akka — becomes
/// this list, unmodified.
public IReadOnlyList Gossiped { get; }
/// Which source resolved these roles.
public RoleSource Source { get; }
/// True when is among (case-insensitive).
public bool HasAdmin => Has(RoleParser.Admin);
/// True when is among (case-insensitive).
public bool HasDriver => Has(RoleParser.Driver);
/// True when is among (case-insensitive).
public bool HasDev => Has(RoleParser.Dev);
/// True when is among , compared case-insensitively.
/// The role to test for.
/// when the role is present; otherwise .
public bool Has(string role) =>
Gossiped.Any(r => string.Equals(r, role, StringComparison.OrdinalIgnoreCase));
/// The first cluster-scoped role in , original spelling preserved,
/// or null when this node carries none.
public string? ClusterRole { get; }
/// The ClusterId this node belongs to (the suffix of ), or null
/// for a legacy / single-mesh node.
public string? ClusterId { get; }
/// Non-null when BOTH Cluster:Roles and OTOPCUA_ROLES were set and their
/// normalized role sets differ — the Cluster:Roles-wins case an operator almost certainly
/// did not intend (choice 5). Observability only: still resolves from
/// Cluster:Roles exactly as usual. Returned rather than logged from this static factory —
/// the caller (Program.cs) logs it once Serilog is configured.
public string? DisagreementWarning { get; }
/// The one factory: resolves the effective roles off 's
/// Cluster:Roles and the process's OTOPCUA_ROLES environment variable.
/// The application configuration.
/// The resolved .
/// Either source names an unknown role.
public static EffectiveRoles Resolve(IConfiguration configuration)
{
ArgumentNullException.ThrowIfNull(configuration);
var configured = configuration.GetSection(ConfiguredRolesKey).Get();
var envRoles = Environment.GetEnvironmentVariable(RoleParser.RolesEnvVar);
return Resolve(configured, envRoles);
}
/// Resolves the effective roles from explicit values — the overload
/// delegates to.
/// The bound Cluster:Roles value.
/// The raw OTOPCUA_ROLES value.
/// The resolved .
/// Either source names an unknown role.
public static EffectiveRoles Resolve(IReadOnlyList? configured, string? envRoles)
{
var configuredNormalized = configured is { Count: > 0 }
? NormalizeAndValidateConfigured(configured)
: null;
// RoleParser.Parse already trims, lower-cases (fully — including a cluster suffix, which is
// intentionally different from the configured path; see ClusterIdFromRole's remarks), dedupes
// and validates.
var envNormalized = !string.IsNullOrWhiteSpace(envRoles)
? RoleParser.Parse(envRoles)
: null;
var warning = BuildDisagreementWarning(configuredNormalized, envNormalized);
if (configuredNormalized is not null)
return new EffectiveRoles(configuredNormalized, RoleSource.Configured, warning);
if (envNormalized is not null)
return new EffectiveRoles(envNormalized, RoleSource.Environment, warning);
return new EffectiveRoles(Array.Empty(), RoleSource.None, null);
}
/// Choice 5: a Warning (not an error) when both sources are set and their normalized
/// role sets differ — this cannot fire when only one source is set, so it is always in that case regardless of the other source's absence.
private static string? BuildDisagreementWarning(string[]? configuredNormalized, string[]? envNormalized)
{
if (configuredNormalized is null || envNormalized is null) return null;
var configuredSet = new HashSet(configuredNormalized, StringComparer.OrdinalIgnoreCase);
var envSet = new HashSet(envNormalized, StringComparer.OrdinalIgnoreCase);
if (configuredSet.SetEquals(envSet)) return null;
return $"{ConfiguredRolesKey} ([{string.Join(",", configuredNormalized)}]) and "
+ $"{RoleParser.RolesEnvVar} ([{string.Join(",", envNormalized)}]) disagree; "
+ $"{ConfiguredRolesKey} wins outright.";
}
/// Normalizes and validates the Cluster:Roles entries: a plain role is trimmed and
/// lower-cased; a cluster role keeps its ClusterId suffix verbatim but gets a normalized
/// (lower-case) cluster- prefix. Throws naming the offending index and value on anything
/// that is neither.
private static string[] NormalizeAndValidateConfigured(IReadOnlyList configured)
{
var result = new string[configured.Count];
for (var i = 0; i < configured.Count; i++)
{
var raw = configured[i];
var trimmed = raw?.Trim() ?? string.Empty;
if (trimmed.Length == 0)
{
throw Unknown(i, raw);
}
if (RoleParser.IsClusterRole(trimmed))
{
var clusterId = RoleParser.ClusterIdFromRole(trimmed);
if (clusterId.Length == 0)
{
throw Unknown(i, raw);
}
result[i] = RoleParser.ClusterRolePrefix + clusterId;
continue;
}
var lowered = trimmed.ToLowerInvariant();
if (lowered is not (RoleParser.Admin or RoleParser.Driver or RoleParser.Dev))
{
throw Unknown(i, raw);
}
result[i] = lowered;
}
return result;
}
private static ArgumentException Unknown(int index, string? raw) =>
new($"{ConfiguredRolesKey}[{index}] = '{raw}' is not a known role. Allowed: {RoleParser.Admin}, "
+ $"{RoleParser.Driver}, {RoleParser.Dev}, or '{RoleParser.ClusterRolePrefix}'.");
}