feat(m9/T26a): read-only inheritance resolve service + GetResolvedTemplateMembersCommand

This commit is contained in:
Joseph Doherty
2026-06-18 12:14:24 -04:00
parent 1ca2e0b130
commit 26e2cdef23
5 changed files with 720 additions and 0 deletions
@@ -0,0 +1,117 @@
namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
/// <summary>
/// Read-only response for <see cref="GetResolvedTemplateMembersCommand"/>: the
/// EFFECTIVE inherited member set for a template, computed fresh from the full
/// inheritance chain (root → leaf, arbitrary depth) and annotated per member
/// with its origin and lock state — plus a staleness summary comparing the
/// template's STORED member rows against this freshly-resolved set.
/// </summary>
/// <remarks>
/// <para>
/// The precedence used to compute the effective member set MIRRORS
/// <c>FlatteningService.ResolveInherited*</c> exactly (derived wins;
/// <c>IsInherited</c> placeholders never shadow the live base value; locked
/// members flagged), so the editor preview agrees with what a deploy would
/// produce. This is the AUTHORING view only — it never mutates stored rows and
/// is not on the deploy path.
/// </para>
/// <para>
/// Member values surfaced here are the inheritance-resolved values BEFORE any
/// composition or instance override is applied — composition is a separate
/// concern owned by the instance flattener, and there are no instances in the
/// template-authoring context.
/// </para>
/// </remarks>
public sealed record ResolvedTemplateMembers
{
/// <summary>The template the member set was resolved for.</summary>
public int TemplateId { get; init; }
/// <summary>The template's name.</summary>
public string TemplateName { get; init; } = string.Empty;
/// <summary>The immediate parent template id, or null when this is a root template.</summary>
public int? ParentTemplateId { get; init; }
/// <summary>The effective resolved attributes (own + transitively inherited).</summary>
public IReadOnlyList<ResolvedTemplateMemberInfo> Attributes { get; init; } = [];
/// <summary>The effective resolved alarms (own + transitively inherited).</summary>
public IReadOnlyList<ResolvedTemplateMemberInfo> Alarms { get; init; } = [];
/// <summary>The effective resolved scripts (own + transitively inherited).</summary>
public IReadOnlyList<ResolvedTemplateMemberInfo> Scripts { get; init; } = [];
/// <summary>The effective resolved native alarm source bindings (own + transitively inherited).</summary>
public IReadOnlyList<ResolvedTemplateMemberInfo> NativeAlarmSources { get; init; } = [];
/// <summary>
/// Staleness summary: whether the template's stored member rows differ from
/// this freshly-resolved set (e.g. a base member added after the derived
/// template was created, or a multi-level inherited member not present in
/// the stored rows), and how many inherited members differ.
/// </summary>
public ResolvedTemplateStaleness Staleness { get; init; } = new();
}
/// <summary>
/// One effective member in a <see cref="ResolvedTemplateMembers"/> set,
/// annotated with where its winning definition came from and its lock state.
/// </summary>
public sealed record ResolvedTemplateMemberInfo
{
/// <summary>The member name (bare; inheritance-resolved members are never path-qualified).</summary>
public string Name { get; init; } = string.Empty;
/// <summary>
/// True when the winning definition lives on an ANCESTOR template rather
/// than on the resolved template itself — i.e. this member is inherited.
/// </summary>
public bool IsInherited { get; init; }
/// <summary>The id of the template that supplied the winning definition.</summary>
public int OriginTemplateId { get; init; }
/// <summary>The name of the template that supplied the winning definition.</summary>
public string OriginTemplateName { get; init; } = string.Empty;
/// <summary>
/// True when the member is locked from override (<c>IsLocked</c> on the
/// winning row) — a derived template cannot change it.
/// </summary>
public bool IsLocked { get; init; }
/// <summary>
/// True when an ANCESTOR marked this member <c>LockedInDerived</c> — the
/// derived template may not override it (rendered read-only with a lock in
/// the editor). Distinct from <see cref="IsLocked"/>: a base may forbid
/// override (<c>LockedInDerived</c>) without the member itself being a
/// locked composition member.
/// </summary>
public bool IsBaseLocked { get; init; }
/// <summary>
/// The effective value for the member, type-appropriate: attribute value,
/// script code, alarm priority/trigger summary, or native-source reference.
/// Provided so the editor preview shows the live (post-resolution) value
/// without re-walking the chain itself. Null when the member type carries
/// no single scalar value.
/// </summary>
public string? EffectiveValue { get; init; }
}
/// <summary>
/// Staleness summary comparing a template's STORED member rows against the
/// freshly-resolved inherited member set.
/// </summary>
public sealed record ResolvedTemplateStaleness
{
/// <summary>
/// True when the stored derived rows differ from the freshly-resolved set —
/// the base changed after the derived template was created, so the editor
/// should surface a "base changed" banner.
/// </summary>
public bool IsStale { get; init; }
/// <summary>
/// The number of inherited members whose freshly-resolved state differs
/// from what the stored rows reflect (missing rows, added base members,
/// changed inherited values). This is the count the editor banner shows.
/// </summary>
public int DifferingMemberCount { get; init; }
}
@@ -7,6 +7,16 @@ public record UpdateTemplateCommand(int TemplateId, string Name, string? Descrip
public record DeleteTemplateCommand(int TemplateId);
public record ValidateTemplateCommand(int TemplateId);
/// <summary>
/// Read-only authoring query (M9/T26a): returns the EFFECTIVE inherited member
/// set for a template — computed fresh from the full inheritance chain
/// (arbitrary depth), annotated per member with origin + lock state — plus a
/// staleness summary comparing the template's stored rows against the resolved
/// set. Feeds the template editor's inheritance preview + base-change banner;
/// never mutates stored rows. Response: <see cref="ResolvedTemplateMembers"/>.
/// </summary>
public record GetResolvedTemplateMembersCommand(int TemplateId);
// Template member operations
public record AddTemplateAttributeCommand(int TemplateId, string Name, string DataType, string? Value, string? Description, string? DataSourceReference, bool IsLocked, string? ElementDataType = null);
public record UpdateTemplateAttributeCommand(int AttributeId, string Name, string DataType, string? Value, string? Description, string? DataSourceReference, bool IsLocked, string? ElementDataType = null);
@@ -244,6 +244,7 @@ public class ManagementActor : ReceiveActor
UpdateTemplateCommand cmd => await HandleUpdateTemplate(sp, cmd, user.Username),
DeleteTemplateCommand cmd => await HandleDeleteTemplate(sp, cmd, user.Username),
ValidateTemplateCommand cmd => await HandleValidateTemplate(sp, cmd),
GetResolvedTemplateMembersCommand cmd => await HandleGetResolvedTemplateMembers(sp, cmd),
// Template members
AddTemplateAttributeCommand cmd => await HandleAddAttribute(sp, cmd, user.Username),
@@ -599,6 +600,20 @@ public class ManagementActor : ReceiveActor
return validationResult;
}
/// <summary>
/// Read-only authoring resolve (M9/T26a): returns the effective inherited
/// member set for a template — computed fresh from the full inheritance
/// chain — plus a staleness summary. Loads every template (children
/// eager-loaded) so the resolver can walk an arbitrary-depth chain; never
/// mutates stored rows.
/// </summary>
private static async Task<object?> HandleGetResolvedTemplateMembers(IServiceProvider sp, GetResolvedTemplateMembersCommand cmd)
{
var repo = sp.GetRequiredService<ITemplateEngineRepository>();
var allTemplates = await repo.GetAllTemplatesAsync();
return TemplateInheritanceResolver.Resolve(cmd.TemplateId, allTemplates);
}
// ========================================================================
// Template folder handlers
// ========================================================================
@@ -0,0 +1,285 @@
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine;
/// <summary>
/// Read-only AUTHORING resolver (M9/T26a). Given a template id and the full
/// template lookup, computes the EFFECTIVE inherited member set fresh from the
/// whole inheritance chain (root → leaf, arbitrary depth, cycle-guarded via
/// <see cref="TemplateResolver.BuildInheritanceChain"/>), annotated per member
/// with origin (own / inherited-from-X) and lock state, plus a staleness
/// summary comparing the template's STORED member rows against the resolved set.
///
/// <para>
/// The inheritance precedence here MIRRORS
/// <see cref="Flattening.FlatteningService"/>'s <c>ResolveInherited*</c> methods
/// EXACTLY so the editor preview agrees with what a deploy would produce:
/// walk base → derived (derived wins); an <c>IsInherited</c> placeholder row on
/// a derived template never shadows the live base value (it only contributes a
/// row when no ancestor defines the member); a locked member, once seen, is not
/// overridden by a downstream template; and an ancestor's
/// <c>LockedInDerived</c> flag is propagated so the editor can render the
/// member read-only.
/// </para>
///
/// <para>
/// This is inheritance only — composition and instance overrides are the
/// instance flattener's concern (there are no instances in the
/// template-authoring context). It NEVER mutates stored rows and is not on the
/// deploy path.
/// </para>
/// </summary>
public static class TemplateInheritanceResolver
{
/// <summary>
/// Resolves the effective inherited member set for <paramref name="templateId"/>.
/// </summary>
/// <param name="templateId">The template to resolve members for.</param>
/// <param name="allTemplates">The complete set of templates (for chain lookups).</param>
/// <returns>
/// The resolved member set (attributes / alarms / scripts / native alarm
/// sources), each annotated with origin + lock state, plus the staleness
/// summary. Returns an empty set when the template id is not found.
/// </returns>
public static ResolvedTemplateMembers Resolve(int templateId, IReadOnlyList<Template> allTemplates)
{
// Duplicate-tolerant lookup (matches TemplateResolver.ResolveAllMembers):
// an Id of 0 is a valid node (import-staging / not-yet-saved rows).
var lookup = CycleDetector.BuildLookup(allTemplates);
if (!lookup.TryGetValue(templateId, out var self))
return new ResolvedTemplateMembers { TemplateId = templateId };
// Root → leaf (derived last). The OWN template is the last element.
var chain = TemplateResolver.BuildInheritanceChain(templateId, lookup);
var attributes = ResolveAttributes(chain, templateId);
var alarms = ResolveAlarms(chain, templateId);
var scripts = ResolveScripts(chain, templateId);
var nativeAlarmSources = ResolveNativeAlarmSources(chain, templateId);
var staleness = ComputeStaleness(self, attributes, alarms, scripts, nativeAlarmSources);
return new ResolvedTemplateMembers
{
TemplateId = templateId,
TemplateName = self.Name,
ParentTemplateId = self.ParentTemplateId,
Attributes = attributes,
Alarms = alarms,
Scripts = scripts,
NativeAlarmSources = nativeAlarmSources,
Staleness = staleness
};
}
// ── per-member-type winners (origin-tracking) ──
/// <summary>The winning row for a member, plus where it came from.</summary>
private sealed record Winner<T>(T Row, Template Origin, bool BaseLocked);
/// <summary>
/// Generic base → derived walk that picks the winning row per member name,
/// replicating FlatteningService precedence:
/// derived wins; an <c>IsInherited</c> placeholder does not shadow a live
/// ancestor value; a locked member is not overridden downstream; the
/// ancestor <c>LockedInDerived</c> flag is tracked.
/// </summary>
private static Dictionary<string, Winner<T>> ResolveWinners<T>(
IReadOnlyList<Template> chain,
Func<Template, IEnumerable<T>> select,
Func<T, string> nameOf,
Func<T, bool> isInherited,
Func<T, bool> isLocked,
Func<T, bool> lockedInDerived)
{
var result = new Dictionary<string, Winner<T>>(StringComparer.Ordinal);
// chain is root-first; walk root → derived so the derived template
// (last) wins, mirroring FlatteningService (which walks its
// most-derived-first chain back-to-front for the same effect).
foreach (var template in chain)
{
foreach (var row in select(template))
{
var name = nameOf(row);
if (result.TryGetValue(name, out var existing))
{
// A locked ancestor row is not overridden by a downstream template.
if (isLocked(existing.Row))
{
if (lockedInDerived(row))
result[name] = existing with { BaseLocked = true };
continue;
}
// IsInherited placeholders never shadow the live ancestor row.
if (isInherited(row))
{
if (lockedInDerived(row))
result[name] = existing with { BaseLocked = true };
continue;
}
}
var baseLocked = (existing?.BaseLocked ?? false) || lockedInDerived(row);
result[name] = new Winner<T>(row, template, baseLocked);
}
}
return result;
}
private static IReadOnlyList<ResolvedTemplateMemberInfo> ResolveAttributes(
IReadOnlyList<Template> chain, int selfId)
{
var winners = ResolveWinners(
chain,
t => t.Attributes,
a => a.Name,
a => a.IsInherited,
a => a.IsLocked,
a => a.LockedInDerived);
return Project(winners, selfId, w => w.Row.Value);
}
private static IReadOnlyList<ResolvedTemplateMemberInfo> ResolveAlarms(
IReadOnlyList<Template> chain, int selfId)
{
var winners = ResolveWinners(
chain,
t => t.Alarms,
a => a.Name,
a => a.IsInherited,
a => a.IsLocked,
a => a.LockedInDerived);
// No single scalar value for an alarm; surface the priority as the preview value.
return Project(winners, selfId, w => w.Row.PriorityLevel.ToString());
}
private static IReadOnlyList<ResolvedTemplateMemberInfo> ResolveScripts(
IReadOnlyList<Template> chain, int selfId)
{
var winners = ResolveWinners(
chain,
t => t.Scripts,
s => s.Name,
s => s.IsInherited,
s => s.IsLocked,
s => s.LockedInDerived);
return Project(winners, selfId, w => w.Row.Code);
}
private static IReadOnlyList<ResolvedTemplateMemberInfo> ResolveNativeAlarmSources(
IReadOnlyList<Template> chain, int selfId)
{
var winners = ResolveWinners(
chain,
t => t.NativeAlarmSources,
s => s.Name,
s => s.IsInherited,
s => s.IsLocked,
s => s.LockedInDerived);
return Project(winners, selfId, w => w.Row.SourceReference);
}
private static IReadOnlyList<ResolvedTemplateMemberInfo> Project<T>(
Dictionary<string, Winner<T>> winners,
int selfId,
Func<Winner<T>, string?> effectiveValue)
{
return winners.Values
.Select(w => new ResolvedTemplateMemberInfo
{
Name = NameOf(w.Row),
IsInherited = w.Origin.Id != selfId,
OriginTemplateId = w.Origin.Id,
OriginTemplateName = w.Origin.Name,
IsLocked = IsLockedOf(w.Row),
IsBaseLocked = w.BaseLocked && w.Origin.Id != selfId,
EffectiveValue = effectiveValue(w)
})
.OrderBy(m => m.Name, StringComparer.Ordinal)
.ToList();
}
private static string NameOf<T>(T row) => row switch
{
TemplateAttribute a => a.Name,
TemplateAlarm a => a.Name,
TemplateScript s => s.Name,
TemplateNativeAlarmSource s => s.Name,
_ => string.Empty
};
private static bool IsLockedOf<T>(T row) => row switch
{
TemplateAttribute a => a.IsLocked,
TemplateAlarm a => a.IsLocked,
TemplateScript s => s.IsLocked,
TemplateNativeAlarmSource s => s.IsLocked,
_ => false
};
// ── staleness ──
/// <summary>
/// Compares the template's STORED member rows against the freshly-resolved
/// set and counts how many INHERITED members drift: a freshly-resolved
/// inherited member with no stored row, or whose stored placeholder value
/// differs from the live resolved value. Own (non-inherited) members never
/// count toward staleness — they are authoritative by definition.
/// </summary>
private static ResolvedTemplateStaleness ComputeStaleness(
Template self,
IReadOnlyList<ResolvedTemplateMemberInfo> attributes,
IReadOnlyList<ResolvedTemplateMemberInfo> alarms,
IReadOnlyList<ResolvedTemplateMemberInfo> scripts,
IReadOnlyList<ResolvedTemplateMemberInfo> nativeAlarmSources)
{
int differing = 0;
differing += CountDrift(attributes,
self.Attributes.ToDictionary(a => a.Name, a => (string?)a.Value, StringComparer.Ordinal));
differing += CountDrift(alarms,
self.Alarms.ToDictionary(a => a.Name, a => (string?)a.PriorityLevel.ToString(), StringComparer.Ordinal));
differing += CountDrift(scripts,
self.Scripts.ToDictionary(s => s.Name, s => (string?)s.Code, StringComparer.Ordinal));
differing += CountDrift(nativeAlarmSources,
self.NativeAlarmSources.ToDictionary(s => s.Name, s => (string?)s.SourceReference, StringComparer.Ordinal));
return new ResolvedTemplateStaleness
{
IsStale = differing > 0,
DifferingMemberCount = differing
};
}
private static int CountDrift(
IReadOnlyList<ResolvedTemplateMemberInfo> resolved,
IReadOnlyDictionary<string, string?> storedValuesByName)
{
int count = 0;
foreach (var m in resolved)
{
if (!m.IsInherited)
continue; // own rows are authoritative — never stale
if (!storedValuesByName.TryGetValue(m.Name, out var storedValue))
{
// Inherited member with no stored placeholder row (e.g. a base
// member added after the derived template was created).
count++;
continue;
}
if (!string.Equals(storedValue, m.EffectiveValue, StringComparison.Ordinal))
count++; // stored placeholder is stale vs. the live base value
}
return count;
}
}