feat(deploymentmanager): IFlatteningPipeline.PreviewAsync — flatten a template+site without an instance row (create-page bindings)
Claude-Session: https://claude.ai/code/session_01G2GHPnbbKGvyyfbr2XBRVH
This commit is contained in:
@@ -81,47 +81,11 @@ public class FlatteningPipeline : IFlatteningPipeline
|
|||||||
if (instance == null)
|
if (instance == null)
|
||||||
return Result<FlatteningPipelineResult>.Failure($"Instance with ID {instanceId} not found.");
|
return Result<FlatteningPipelineResult>.Failure($"Instance with ID {instanceId} not found.");
|
||||||
|
|
||||||
Task<Commons.Entities.Templates.Template?> LoadTemplate(int id) =>
|
var graph = await LoadTemplateGraphAsync(instance.TemplateId, session, cancellationToken);
|
||||||
_templateRepo.GetTemplateWithChildrenAsync(id, cancellationToken);
|
if (graph is null)
|
||||||
|
|
||||||
// Build template chain
|
|
||||||
var templateChain = await session.GetChainAsync(instance.TemplateId, LoadTemplate);
|
|
||||||
if (templateChain.Count == 0)
|
|
||||||
return Result<FlatteningPipelineResult>.Failure("Template chain is empty.");
|
return Result<FlatteningPipelineResult>.Failure("Template chain is empty.");
|
||||||
|
|
||||||
// Build composition maps, walking nested compositions so the flattener
|
var (templateChain, compositionMap, composedChains) = graph.Value;
|
||||||
// can resolve composed-of-composed attributes / alarms / scripts (e.g.
|
|
||||||
// a parent that composes Pump where Pump itself composes AlarmSensor
|
|
||||||
// produces "Pump.AlarmSensor.SensorReading").
|
|
||||||
var compositionMap = new Dictionary<int, IReadOnlyList<Commons.Entities.Templates.TemplateComposition>>();
|
|
||||||
var composedChains = new Dictionary<int, IReadOnlyList<Commons.Entities.Templates.Template>>();
|
|
||||||
var processedTemplateIds = new HashSet<int>();
|
|
||||||
var pendingChains = new Queue<IReadOnlyList<Commons.Entities.Templates.Template>>();
|
|
||||||
|
|
||||||
pendingChains.Enqueue(templateChain);
|
|
||||||
while (pendingChains.Count > 0)
|
|
||||||
{
|
|
||||||
var chain = pendingChains.Dequeue();
|
|
||||||
foreach (var template in chain)
|
|
||||||
{
|
|
||||||
if (!processedTemplateIds.Add(template.Id)) continue;
|
|
||||||
|
|
||||||
var compositions = await session.GetCompositionsAsync(
|
|
||||||
template.Id,
|
|
||||||
id => _templateRepo.GetCompositionsByTemplateIdAsync(id, cancellationToken));
|
|
||||||
if (compositions.Count == 0) continue;
|
|
||||||
|
|
||||||
compositionMap[template.Id] = compositions;
|
|
||||||
foreach (var comp in compositions)
|
|
||||||
{
|
|
||||||
if (composedChains.ContainsKey(comp.ComposedTemplateId)) continue;
|
|
||||||
|
|
||||||
var composedChain = await session.GetChainAsync(comp.ComposedTemplateId, LoadTemplate);
|
|
||||||
composedChains[comp.ComposedTemplateId] = composedChain;
|
|
||||||
pendingChains.Enqueue(composedChain);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load data connections for the site
|
// Load data connections for the site
|
||||||
var dataConnections = await session.GetDataConnectionsAsync(
|
var dataConnections = await session.GetDataConnectionsAsync(
|
||||||
@@ -216,6 +180,86 @@ public class FlatteningPipeline : IFlatteningPipeline
|
|||||||
new FlatteningPipelineResult(config, hash, validation));
|
new FlatteningPipelineResult(config, hash, validation));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<Result<FlattenedConfiguration>> PreviewAsync(
|
||||||
|
int templateId,
|
||||||
|
int siteId,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var session = CreateSession();
|
||||||
|
|
||||||
|
var graph = await LoadTemplateGraphAsync(templateId, session, cancellationToken);
|
||||||
|
if (graph is null)
|
||||||
|
return Result<FlattenedConfiguration>.Failure($"Template {templateId} not found or its chain is empty.");
|
||||||
|
|
||||||
|
var dataConnections = await session.GetDataConnectionsAsync(
|
||||||
|
siteId,
|
||||||
|
id => LoadDataConnectionsAsync(id, cancellationToken));
|
||||||
|
|
||||||
|
// A stand-in instance with no overrides and no bindings: the flattener sees
|
||||||
|
// exactly what a freshly created instance would, and nothing is persisted.
|
||||||
|
var preview = new Commons.Entities.Instances.Instance("(preview)")
|
||||||
|
{
|
||||||
|
TemplateId = templateId,
|
||||||
|
SiteId = siteId
|
||||||
|
};
|
||||||
|
|
||||||
|
return _flatteningService.Flatten(
|
||||||
|
preview, graph.Value.Chain, graph.Value.CompositionMap, graph.Value.ComposedChains, dataConnections);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Loads the template inheritance chain for <paramref name="templateId"/> plus the
|
||||||
|
/// composition maps, walking nested compositions so the flattener can resolve
|
||||||
|
/// composed-of-composed members (e.g. a parent composing Pump where Pump itself
|
||||||
|
/// composes AlarmSensor produces "Pump.AlarmSensor.SensorReading").
|
||||||
|
/// Returns <see langword="null"/> when the chain is empty (unknown template).
|
||||||
|
/// </summary>
|
||||||
|
private async Task<(IReadOnlyList<Commons.Entities.Templates.Template> Chain,
|
||||||
|
Dictionary<int, IReadOnlyList<Commons.Entities.Templates.TemplateComposition>> CompositionMap,
|
||||||
|
Dictionary<int, IReadOnlyList<Commons.Entities.Templates.Template>> ComposedChains)?>
|
||||||
|
LoadTemplateGraphAsync(int templateId, FlattenSession session, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
Task<Commons.Entities.Templates.Template?> LoadTemplate(int id) =>
|
||||||
|
_templateRepo.GetTemplateWithChildrenAsync(id, cancellationToken);
|
||||||
|
|
||||||
|
var templateChain = await session.GetChainAsync(templateId, LoadTemplate);
|
||||||
|
if (templateChain.Count == 0)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var compositionMap = new Dictionary<int, IReadOnlyList<Commons.Entities.Templates.TemplateComposition>>();
|
||||||
|
var composedChains = new Dictionary<int, IReadOnlyList<Commons.Entities.Templates.Template>>();
|
||||||
|
var processedTemplateIds = new HashSet<int>();
|
||||||
|
var pendingChains = new Queue<IReadOnlyList<Commons.Entities.Templates.Template>>();
|
||||||
|
|
||||||
|
pendingChains.Enqueue(templateChain);
|
||||||
|
while (pendingChains.Count > 0)
|
||||||
|
{
|
||||||
|
var chain = pendingChains.Dequeue();
|
||||||
|
foreach (var template in chain)
|
||||||
|
{
|
||||||
|
if (!processedTemplateIds.Add(template.Id)) continue;
|
||||||
|
|
||||||
|
var compositions = await session.GetCompositionsAsync(
|
||||||
|
template.Id,
|
||||||
|
id => _templateRepo.GetCompositionsByTemplateIdAsync(id, cancellationToken));
|
||||||
|
if (compositions.Count == 0) continue;
|
||||||
|
|
||||||
|
compositionMap[template.Id] = compositions;
|
||||||
|
foreach (var comp in compositions)
|
||||||
|
{
|
||||||
|
if (composedChains.ContainsKey(comp.ComposedTemplateId)) continue;
|
||||||
|
|
||||||
|
var composedChain = await session.GetChainAsync(comp.ComposedTemplateId, LoadTemplate);
|
||||||
|
composedChains[comp.ComposedTemplateId] = composedChain;
|
||||||
|
pendingChains.Enqueue(composedChain);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (templateChain, compositionMap, composedChains);
|
||||||
|
}
|
||||||
|
|
||||||
private async Task<IReadOnlyDictionary<int, DataConnection>> LoadDataConnectionsAsync(
|
private async Task<IReadOnlyDictionary<int, DataConnection>> LoadDataConnectionsAsync(
|
||||||
int siteId,
|
int siteId,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
|
|||||||
@@ -39,6 +39,21 @@ public interface IFlatteningPipeline
|
|||||||
bool validateScripts = true,
|
bool validateScripts = true,
|
||||||
FlattenSession? session = null);
|
FlattenSession? session = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Flattens <paramref name="templateId"/> as if an instance with no overrides and no
|
||||||
|
/// bindings existed at <paramref name="siteId"/>. Attribute list only — no validation,
|
||||||
|
/// no revision hash, nothing persisted. Used by the Create Instance page to show the
|
||||||
|
/// module groups before the instance row exists.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="templateId">Id of the template to preview.</param>
|
||||||
|
/// <param name="siteId">Id of the target site, whose data connections resolve references.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The flattened configuration of the hypothetical instance, or a failure result.</returns>
|
||||||
|
Task<Result<FlattenedConfiguration>> PreviewAsync(
|
||||||
|
int templateId,
|
||||||
|
int siteId,
|
||||||
|
CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Creates a fresh <see cref="FlattenSession"/> bound to this pipeline's
|
/// Creates a fresh <see cref="FlattenSession"/> bound to this pipeline's
|
||||||
/// watermark, for a caller that wants to share one across a batch of
|
/// watermark, for a caller that wants to share one across a batch of
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
using NSubstitute;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pins <c>PreviewAsync</c>: the Create Instance page must see exactly the attribute
|
||||||
|
/// set a freshly created, un-overridden instance flattens to — including composed
|
||||||
|
/// module members — without any instance row existing.
|
||||||
|
/// </summary>
|
||||||
|
public class FlatteningPipelinePreviewTests
|
||||||
|
{
|
||||||
|
private const int TemplateId = 10, ModuleTemplateId = 11, SiteId = 20, InstanceId = 30;
|
||||||
|
|
||||||
|
private readonly ITemplateEngineRepository _templateRepo = Substitute.For<ITemplateEngineRepository>();
|
||||||
|
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
|
||||||
|
private readonly ISharedSchemaRepository _sharedSchemaRepo = Substitute.For<ISharedSchemaRepository>();
|
||||||
|
private readonly FlatteningPipeline _sut;
|
||||||
|
|
||||||
|
public FlatteningPipelinePreviewTests()
|
||||||
|
{
|
||||||
|
_sharedSchemaRepo.ListAsync(Arg.Any<CancellationToken>()).Returns([]);
|
||||||
|
_sut = new FlatteningPipeline(_templateRepo, _siteRepo, new FlatteningService(), new ValidationService(),
|
||||||
|
new RevisionHashService(), _sharedSchemaRepo, new TemplateGraphWatermark());
|
||||||
|
|
||||||
|
// Parent template with one direct data-sourced attribute, composing a module with one.
|
||||||
|
var module = new Template("Receiver") { Id = ModuleTemplateId };
|
||||||
|
module.Attributes.Add(new TemplateAttribute("MoveInFlag")
|
||||||
|
{
|
||||||
|
DataType = DataType.Boolean,
|
||||||
|
DataSourceReference = "MoveInFlag"
|
||||||
|
});
|
||||||
|
var parent = new Template("Line") { Id = TemplateId };
|
||||||
|
parent.Attributes.Add(new TemplateAttribute("Running")
|
||||||
|
{
|
||||||
|
DataType = DataType.Boolean,
|
||||||
|
DataSourceReference = "Running"
|
||||||
|
});
|
||||||
|
var composition = new TemplateComposition("Left")
|
||||||
|
{
|
||||||
|
TemplateId = TemplateId,
|
||||||
|
ComposedTemplateId = ModuleTemplateId
|
||||||
|
};
|
||||||
|
|
||||||
|
_templateRepo.GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>()).Returns(parent);
|
||||||
|
_templateRepo.GetTemplateWithChildrenAsync(ModuleTemplateId, Arg.Any<CancellationToken>()).Returns(module);
|
||||||
|
_templateRepo.GetCompositionsByTemplateIdAsync(TemplateId, Arg.Any<CancellationToken>()).Returns([composition]);
|
||||||
|
_templateRepo.GetCompositionsByTemplateIdAsync(ModuleTemplateId, Arg.Any<CancellationToken>()).Returns([]);
|
||||||
|
_templateRepo.GetAllSharedScriptsAsync(Arg.Any<CancellationToken>()).Returns([]);
|
||||||
|
_templateRepo.GetInstanceByIdAsync(InstanceId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(new Instance("Line-01") { Id = InstanceId, TemplateId = TemplateId, SiteId = SiteId });
|
||||||
|
_siteRepo.GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns([new DataConnection("MxGateway", "MxGateway", SiteId) { Id = 1 }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Preview_matches_flatten_of_fresh_instance()
|
||||||
|
{
|
||||||
|
var preview = await _sut.PreviewAsync(TemplateId, SiteId);
|
||||||
|
var real = await _sut.FlattenAndValidateAsync(InstanceId, validateScripts: false);
|
||||||
|
|
||||||
|
// Result.Error throws on a success, so the message is only read on failure.
|
||||||
|
Assert.True(preview.IsSuccess, preview.IsSuccess ? "" : preview.Error);
|
||||||
|
Assert.True(real.IsSuccess, real.IsSuccess ? "" : real.Error);
|
||||||
|
|
||||||
|
var expected = real.Value.Configuration.Attributes
|
||||||
|
.Select(a => (a.CanonicalName, a.DefaultDataSourceReference ?? a.DataSourceReference))
|
||||||
|
.OrderBy(x => x.Item1, StringComparer.Ordinal).ToList();
|
||||||
|
var actual = preview.Value.Attributes
|
||||||
|
.Select(a => (a.CanonicalName, a.DefaultDataSourceReference ?? a.DataSourceReference))
|
||||||
|
.OrderBy(x => x.Item1, StringComparer.Ordinal).ToList();
|
||||||
|
|
||||||
|
Assert.Equal(expected, actual);
|
||||||
|
Assert.Contains(actual, a => a.Item1 == "Left.MoveInFlag");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Preview_unknown_template_fails()
|
||||||
|
{
|
||||||
|
var r = await _sut.PreviewAsync(999, SiteId);
|
||||||
|
Assert.True(r.IsFailure);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Preview_never_touches_instance_repository()
|
||||||
|
{
|
||||||
|
await _sut.PreviewAsync(TemplateId, SiteId);
|
||||||
|
await _templateRepo.DidNotReceive().GetInstanceByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user