perf(templates): resync and resolved-members read only the chain/subtree (ScadaBridge#89)
The last two whole-library template reads are gone. Both fed the inheritance-only TemplateInheritanceResolver, which walks one template's parent chain and never follows compositions. - TemplateService.ResyncInheritedMembersAsync (operator repair, CLI + editor) now reads #86's GetTemplateReconcileClosureAsync (derived subtree + the template's chain, tracked). When nothing derives from the template the closure is empty, so it falls back to the new tracked GetTemplateChainAsync - resyncing a leaf reads only its own chain. - ManagementActor.HandleGetResolvedTemplateMembers now reads GetTemplateChainAsync(id, trackChanges: false): the chain alone, untracked, with script bodies (the resolver projects script code, so #66's body-free analysis closure would not be equivalent). The chain walk is factored out of TemplateReconcileClosure into CollectChainAsync (one load per level, stops on parent cycles and dangling parents) and shared by both. Evidence: - TemplateChainReadTests (#86 fixture): for every template plus an unknown id, the closure-backed resync issues exactly the writes, audit row and result of the whole-graph resync with GetAllTemplatesAsync wired to throw; the resolver answers identically from the chain and the whole graph. 17 of these fail against the old service; 13 fail with the leaf chain fallback removed (mutation-checked). - TemplateChainRepositoryTests (SQLite, recorded SQL): a 4-deep chain loads 4 templates / 8 attributes instead of 46 / 92, one split-query set per level, untracked on request and tracked for the resync. - ResolvedTemplateMembersReadTests: the actor answers from the untracked chain read and never calls GetAllTemplatesAsync (fails on the old actor). Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
+16
@@ -83,6 +83,22 @@ public interface ITemplateEngineRepository
|
||||
/// <returns>A task that resolves to the subtree followed by the template's chain.</returns>
|
||||
Task<IReadOnlyList<Template>> GetTemplateReconcileClosureAsync(int templateId, CancellationToken cancellationToken = default);
|
||||
/// <summary>
|
||||
/// Returns the fully-loaded templates (the <see cref="GetAllTemplatesAsync"/> shape: attributes,
|
||||
/// alarms, scripts with bodies, compositions, native alarm sources) of
|
||||
/// <paramref name="templateId"/>'s inheritance chain only — the template, its parent,
|
||||
/// grandparent, … (see
|
||||
/// <see cref="ZB.MOM.WW.ScadaBridge.Commons.Types.Templates.TemplateReconcileClosure.CollectChainAsync"/>).
|
||||
/// That is everything <c>TemplateInheritanceResolver.Resolve</c> reads for one template (Gitea #89):
|
||||
/// it backs the read-only resolved-members query (<paramref name="trackChanges"/> = false) and the
|
||||
/// inherited-member resync of a template with no descendants (tracked, because the resync writes
|
||||
/// through these entities). Returns an empty list when the template does not exist.
|
||||
/// </summary>
|
||||
/// <param name="templateId">The template whose chain to load.</param>
|
||||
/// <param name="trackChanges">Whether the returned entities are tracked by the context.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A task that resolves to the template followed by its ancestors.</returns>
|
||||
Task<IReadOnlyList<Template>> GetTemplateChainAsync(int templateId, bool trackChanges, CancellationToken cancellationToken = default);
|
||||
/// <summary>
|
||||
/// Returns an untracked identity/edge projection of every template (no children), ordered by name.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
|
||||
@@ -78,6 +78,44 @@ public static class TemplateReconcileClosure
|
||||
|
||||
// 2. The root's own inheritance chain, one query per level. A level already loaded as
|
||||
// part of the subtree means a parent cycle — the chain ends there.
|
||||
await WalkChainAsync(templateId, loaded, result, loadByIds, cancellationToken).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collects only the inheritance chain of <paramref name="templateId"/>: the template itself,
|
||||
/// its parent, grandparent, … (Gitea #89). This is everything
|
||||
/// <c>TemplateInheritanceResolver.Resolve</c> reads for one template — the resolver is
|
||||
/// inheritance-only — so it backs the read-only resolved-members query, and the inherited-member
|
||||
/// resync of a template nobody derives from. One <paramref name="loadByIds"/> call per level;
|
||||
/// a parent cycle or a dangling parent edge ends the chain.
|
||||
/// </summary>
|
||||
/// <param name="templateId">The template whose chain to load.</param>
|
||||
/// <param name="loadByIds">Loads the templates with the given ids (unknown ids are omitted).</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The template followed by its ancestors, each once; empty when the template is unknown.</returns>
|
||||
public static async Task<IReadOnlyList<Template>> CollectChainAsync(
|
||||
int templateId,
|
||||
Func<IReadOnlyCollection<int>, CancellationToken, Task<IReadOnlyList<Template>>> loadByIds,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(loadByIds);
|
||||
var result = new List<Template>();
|
||||
await WalkChainAsync(templateId, new Dictionary<int, Template>(), result, loadByIds, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Walks templateId's parent chain upward, loading each level not already in `loaded` (one
|
||||
// loadByIds call per level) and appending it to `result`. Ends on a repeated id (a parent
|
||||
// cycle) or a template that does not exist (a dangling parent edge, or an unknown root).
|
||||
private static async Task WalkChainAsync(
|
||||
int templateId,
|
||||
Dictionary<int, Template> loaded,
|
||||
List<Template> result,
|
||||
Func<IReadOnlyCollection<int>, CancellationToken, Task<IReadOnlyList<Template>>> loadByIds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var requested = new HashSet<int>();
|
||||
int? nextId = templateId;
|
||||
while (nextId is int id && requested.Add(id))
|
||||
@@ -97,7 +135,5 @@ public static class TemplateReconcileClosure
|
||||
result.Add(template);
|
||||
nextId = template.ParentTemplateId;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
+20
-2
@@ -161,8 +161,26 @@ public class TemplateEngineRepository : ITemplateEngineRepository
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
// The tracked, fully-included template shape shared by GetAllTemplatesAsync and
|
||||
// GetTemplateReconcileClosureAsync.
|
||||
/// <inheritdoc />
|
||||
// One fully-included query per chain level (Gitea #89). Chains are short (a handful of
|
||||
// levels), so this is a few small reads instead of the whole library.
|
||||
public Task<IReadOnlyList<Template>> GetTemplateChainAsync(int templateId, bool trackChanges, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return TemplateReconcileClosure.CollectChainAsync(
|
||||
templateId,
|
||||
async (ids, ct) =>
|
||||
{
|
||||
var idList = ids.ToList();
|
||||
var query = FullTemplateGraph().Where(t => idList.Contains(t.Id));
|
||||
if (!trackChanges)
|
||||
query = query.AsNoTracking();
|
||||
return await query.ToListAsync(ct);
|
||||
},
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
// The tracked, fully-included template shape shared by GetAllTemplatesAsync,
|
||||
// GetTemplateReconcileClosureAsync and GetTemplateChainAsync.
|
||||
private IQueryable<Template> FullTemplateGraph()
|
||||
{
|
||||
return _context.Templates
|
||||
|
||||
@@ -869,15 +869,15 @@ public class ManagementActor : ReceiveActor
|
||||
/// <summary>
|
||||
/// Read-only authoring resolve: 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.
|
||||
/// chain — plus a staleness summary. The resolver is inheritance-only, so it
|
||||
/// loads just the template's own chain, untracked (Gitea #89) — never the
|
||||
/// whole library; 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);
|
||||
var chain = await repo.GetTemplateChainAsync(cmd.TemplateId, trackChanges: false);
|
||||
return TemplateInheritanceResolver.Resolve(cmd.TemplateId, chain);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1220,7 +1220,15 @@ public class TemplateService
|
||||
string user,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var all = await _repository.GetAllTemplatesAsync(cancellationToken) ?? Array.Empty<Template>();
|
||||
// Every target's chain runs through templateId and on up its own chain, and the
|
||||
// resolver is inheritance-only, so the subtree + templateId's chain is everything
|
||||
// the resync reads (#89, reusing #86's closure). A template nobody derives from
|
||||
// has an empty reconcile closure; it still needs its own chain to resync itself.
|
||||
var all = await _repository.GetTemplateReconcileClosureAsync(templateId, cancellationToken)
|
||||
?? Array.Empty<Template>();
|
||||
if (all.Count == 0)
|
||||
all = await _repository.GetTemplateChainAsync(templateId, trackChanges: true, cancellationToken)
|
||||
?? Array.Empty<Template>();
|
||||
var byId = BuildTemplateLookup(all);
|
||||
if (!byId.TryGetValue(templateId, out var root))
|
||||
return Result<ResyncInheritedMembersResult>.Failure($"Template with ID {templateId} not found.");
|
||||
|
||||
Reference in New Issue
Block a user