perf(transport,management): bundle export resolves names from projections; import memoises name and connection lookups (MGT-5, TRN-11, WP6 task 6.7)
MGT-5: HandleExportBundle resolves template names against GetTemplateStubsAsync (untracked Id/Name projection) and instance names against the new ITemplateEngineRepository.GetInstanceNamesAsync (Id, UniqueName) instead of GetAllTemplatesAsync (tracked full graph incl. script bodies) + GetAllInstancesAsync (every instance with 4 child collections). The exporter still loads the selected rows itself. Per export: 1 tracked multi-Include template query + 5 instance split queries (whole tables, tracked) -> 2 narrow untracked projections. TRN-11 (narrow subset, BundleImporter is also WP2's file): - Derived-template apply: owner/base root names were each a query (unindexable), twice per derived template; now one (Id, Name, IsDerived) projection into a case-insensitive index, falling back to the live query only when a name has no base row (the loop only creates/deletes derived templates, so a base hit is always current). N derived templates: 2N full-scan queries -> 1 projection (+ misses). - Preview validation: the referenced-connection check memoises each target site's connection names (one read per site instead of per reference). Not done here (left for the integrator / WP2 overlap): bulk-loading the per-row by-name lookups in the main apply loops (BI:3789-4449) and the DependencyResolver per-id seed loads.
This commit is contained in:
@@ -323,6 +323,14 @@ public interface ITemplateEngineRepository
|
||||
/// <returns>The site's instances, shallow and untracked.</returns>
|
||||
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// MGT-5: every instance's (Id, UniqueName) — the name index bundle export resolves
|
||||
/// <c>--instances</c> against, instead of loading every instance with its child collections.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>One (Id, UniqueName) pair per instance.</returns>
|
||||
Task<IReadOnlyList<(int Id, string UniqueName)>> GetInstanceNamesAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// TPL-4: whether a template other than <paramref name="excludeTemplateId"/> named
|
||||
/// <paramref name="name"/> (case-insensitively) already sits in <paramref name="folderId"/>
|
||||
|
||||
+10
@@ -553,6 +553,16 @@ public class TemplateEngineRepository : ITemplateEngineRepository
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<(int Id, string UniqueName)>> GetInstanceNamesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rows = await _context.Instances
|
||||
.AsNoTracking()
|
||||
.Select(i => new { i.Id, i.UniqueName })
|
||||
.ToListAsync(cancellationToken);
|
||||
return rows.Select(r => (r.Id, r.UniqueName)).ToList();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> TemplateNameExistsInFolderAsync(
|
||||
int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default)
|
||||
|
||||
@@ -4380,7 +4380,10 @@ public class ManagementActor : ReceiveActor
|
||||
var inboundRepo = sp.GetRequiredService<IInboundApiRepository>();
|
||||
var siteRepo = sp.GetRequiredService<ISiteRepository>();
|
||||
|
||||
var templates = await templateRepo.GetAllTemplatesAsync();
|
||||
// MGT-5: names resolve against narrow (Id, Name) projections — the exporter loads the
|
||||
// selected rows itself, so the full tracked template graph and every instance with its
|
||||
// child collections were materialised here only to map names to ids.
|
||||
var templates = await templateRepo.GetTemplateStubsAsync();
|
||||
var sharedScripts = await templateRepo.GetAllSharedScriptsAsync();
|
||||
var externalSystems = await externalRepo.GetAllExternalSystemsAsync();
|
||||
var dbConnections = await externalRepo.GetAllDatabaseConnectionsAsync();
|
||||
@@ -4393,7 +4396,7 @@ public class ManagementActor : ReceiveActor
|
||||
// Site/instance-scoped selection. Sites match on SiteIdentifier
|
||||
// (preferred) or Name; instances match on UniqueName.
|
||||
var sites = await siteRepo.GetAllSitesAsync();
|
||||
var instances = await templateRepo.GetAllInstancesAsync();
|
||||
var instances = await templateRepo.GetInstanceNamesAsync();
|
||||
|
||||
int[] ResolveIds<T>(IReadOnlyList<T> all, IReadOnlyList<string>? names,
|
||||
Func<T, string> getName, Func<T, int> getId, string entityType)
|
||||
|
||||
@@ -207,8 +207,28 @@ public sealed partial class BundleImporter
|
||||
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
var service = new TemplateService(_templateRepo, _auditService);
|
||||
|
||||
// TRN-11: every owner/base root name was looked up with its own
|
||||
// `t.Name.ToLower() == lower` query (unindexable) — twice per derived template. The
|
||||
// (Id, Name, IsDerived) projection of the whole table is loaded ONCE into a
|
||||
// case-insensitive index instead (narrow: no members, no script bodies). This loop
|
||||
// only ever creates or deletes DERIVED templates, so a hit on a base row is always
|
||||
// current; a name with no base row in the index falls back to the live query, so the
|
||||
// derived-only / not-found diagnostics still see what earlier rows wrote.
|
||||
Dictionary<string, List<TemplateRow>>? templateRowsByName = null;
|
||||
async Task<IReadOnlyList<TemplateRow>> Named(string name)
|
||||
{
|
||||
if (templateRowsByName is null)
|
||||
{
|
||||
var all = await _dbContext.Templates.AsNoTracking()
|
||||
.Select(t => new TemplateRow(t.Id, t.Name, t.IsDerived))
|
||||
.ToListAsync(ct).ConfigureAwait(false);
|
||||
templateRowsByName = all
|
||||
.GroupBy(r => r.Name, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
if (templateRowsByName.TryGetValue(name, out var cached) && cached.Any(r => !r.IsDerived))
|
||||
return cached;
|
||||
|
||||
var lower = name.ToLower();
|
||||
return await _dbContext.Templates.AsNoTracking()
|
||||
.Where(t => t.Name.ToLower() == lower)
|
||||
|
||||
@@ -5369,6 +5369,8 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
}
|
||||
}
|
||||
|
||||
// TRN-11: one connection read per target site, not one per referencing row.
|
||||
var targetConnNamesBySiteId = new Dictionary<int, HashSet<string>>();
|
||||
foreach (var (site, name) in referencedConnections)
|
||||
{
|
||||
if (bundleConnectionRefs.Contains((site, name))) continue; // carried → creatable
|
||||
@@ -5379,8 +5381,13 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
&& mapping.TargetConnectionName is { Length: > 0 } tn
|
||||
? tn
|
||||
: name;
|
||||
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
|
||||
if (!conns.Any(c => string.Equals(c.Name, targetName, StringComparison.Ordinal)))
|
||||
if (!targetConnNamesBySiteId.TryGetValue(targetSite.Id, out var connNames))
|
||||
{
|
||||
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
|
||||
connNames = new HashSet<string>(conns.Select(c => c.Name), StringComparer.Ordinal);
|
||||
targetConnNamesBySiteId[targetSite.Id] = connNames;
|
||||
}
|
||||
if (!connNames.Contains(targetName))
|
||||
{
|
||||
errors.Add(
|
||||
$"Connection '{site}/{name}' is referenced by the bundle but is neither carried in "
|
||||
|
||||
@@ -4062,14 +4062,15 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
|
||||
// The repository fan-out HandleExportBundle does at the top of its body.
|
||||
// Tests that only exercise role gating still need these resolved.
|
||||
_templateRepo.GetAllTemplatesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template>());
|
||||
// MGT-5: template and instance names resolve against narrow projections.
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub>());
|
||||
_templateRepo.GetAllSharedScriptsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Entities.Scripts.SharedScript>());
|
||||
// Export now also fans out to instances (template repo) and sites
|
||||
// (site repo) for the site/instance-scoped selection.
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>());
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)>());
|
||||
|
||||
var siteRepo = Substitute.For<ISiteRepository>();
|
||||
siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
|
||||
@@ -4161,8 +4162,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
// curated message must surface verbatim to the caller.
|
||||
AddBundleSubstitutes();
|
||||
// No templates in the repo; the export selection names one anyway.
|
||||
_templateRepo.GetAllTemplatesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template>());
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub>());
|
||||
|
||||
var cmd = new ExportBundleCommand(
|
||||
All: false,
|
||||
@@ -4187,6 +4188,36 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
Assert.Contains("DoesNotExist", response.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MGT-5 (WP6 6.7): export resolves names against the (Id, Name) projections and never
|
||||
/// materialises the full template graph or every instance with its child collections.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ExportBundleCommand_ResolvesNamesFromProjections_NotFullGraphs()
|
||||
{
|
||||
var (exporter, _) = AddBundleSubstitutes();
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub> { new(7, "PumpBase", null, null, false, null) });
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
Arg.Do<Commons.Types.Transport.ExportSelection>(s => captured = s),
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Task.FromResult<Stream>(new MemoryStream(new byte[] { 1 })));
|
||||
|
||||
var cmd = new ExportBundleCommand(
|
||||
All: false, TemplateNames: new[] { "PumpBase" }, SharedScriptNames: null,
|
||||
ExternalSystemNames: null, DatabaseConnectionNames: null,
|
||||
NotificationListNames: null, SmtpConfigurationNames: null, ApiMethodNames: null,
|
||||
IncludeDependencies: false, Passphrase: null, SourceEnvironment: "test-env");
|
||||
CreateActor().Tell(Envelope(cmd, "Designer"));
|
||||
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal(new[] { 7 }, captured!.TemplateIds);
|
||||
_templateRepo.DidNotReceive().GetAllTemplatesAsync(Arg.Any<CancellationToken>());
|
||||
_templateRepo.DidNotReceive().GetAllInstancesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that export bundle command, when with site and instance names, resolves to ids.</summary>
|
||||
[Fact]
|
||||
public void ExportBundleCommand_WithSiteAndInstanceNames_ResolvesToIds()
|
||||
@@ -4204,12 +4235,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
new("North Plant", "NORTH-01") { Id = 11 },
|
||||
new("East Plant", "EAST-02") { Id = 22 },
|
||||
});
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>
|
||||
{
|
||||
new("NORTH-01.Pump1") { Id = 101, SiteId = 11, TemplateId = 1 },
|
||||
new("NORTH-01.Pump2") { Id = 102, SiteId = 11, TemplateId = 1 },
|
||||
});
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)> { (101, "NORTH-01.Pump1"), (102, "NORTH-01.Pump2") });
|
||||
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
@@ -4255,12 +4282,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
new("North Plant", "NORTH-01") { Id = 11 },
|
||||
new("East Plant", "EAST-02") { Id = 22 },
|
||||
});
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>
|
||||
{
|
||||
new("NORTH-01.Pump1") { Id = 101, SiteId = 11, TemplateId = 1 },
|
||||
new("EAST-02.Pump9") { Id = 909, SiteId = 22, TemplateId = 1 },
|
||||
});
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)> { (101, "NORTH-01.Pump1"), (909, "EAST-02.Pump9") });
|
||||
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
|
||||
Reference in New Issue
Block a user