Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs
T
Joseph Doherty 59817f5017 perf(deployment,template-engine): batched untracked staleness loads, staging-failure detach, lock-held Disabled re-check, targeted single-entity loads (DEP-4, DEP-5, DEP-6, TPL-4, WP6 task 6.6)
DEP-4: new ITemplateEngineRepository.GetInstancesByIdsUntrackedAsync (one
AsNoTracking split query per 500-id chunk). GetInstanceStalenessAsync preloads
each chunk into its FlattenSession; FlattenCoreAsync takes a preloaded
instance (consumed once) before falling back to the tracked per-instance load.
Deploy sessions never preload, so prepare keeps its tracked load.
  Throwaway harness, SQLite, 1,000 instances x 50 overrides:
  before: 5,000 reader commands, 51,000 tracked entities
  after:  10 reader commands, 0 tracked entities
  (wall time on in-process SQLite 2.7 s -> 2.3 s; the win on SQL Server is
  the 4,990 saved round-trips and the change tracker staying empty)

DEP-5: AddPendingDeploymentAsync supersedes prior rows with a set-based
delete (DeletePendingWhereAsync) instead of tracked key stubs, and a failed
staging save calls DetachPendingChanges under dbGate so it cannot poison the
next instance's staging save on the shared bulk context.
  Regression: prior row purged between supersede and save -> before:
  DbUpdateConcurrencyException; after: stages cleanly.

DEP-6: bulk prepare (reconcileGate != null) re-reads the instance state
untracked (new IDeploymentManagerRepository.GetInstanceStateAsync) once the
operation lock is held; Disabled -> reported in SkippedInstances with the
Disabled reason, never flattened/sent/re-enabled. Placed at the top of
PrepareUnderLockAsync so it is independent of WP7's lock-ordering change.

TPL-4: area delete uses the new shallow untracked GetInstancesBySiteIdShallowAsync;
SetAlarmOverride and Delete{Attribute,Alarm,Script} read the analysis closure
instead of the whole template table; MoveTemplate's collision check is the new
TemplateNameExistsInFolderAsync (one folder's names). SiteService already used
the include-free ISiteRepository read (unchanged).
2026-12-03 10:09:41 -05:00

470 lines
23 KiB
C#

using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.Commons.Types;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Validation;
using ZB.MOM.WW.ScadaBridge.TemplateEngine;
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Services;
/// <summary>
/// Instance CRUD operations.
/// - Create instance from template at site
/// - Assign to area
/// - Override non-locked attribute values
/// - Cannot add or remove attributes (only override existing ones)
/// - Per-attribute connection binding (bulk assignment support)
/// - Enabled/disabled state. Concurrent edits are last-write-wins — there is no
/// version token or conflict detection on instance state, matching the design
/// decision (Component-TemplateEngine.md: "Concurrent editing uses
/// last-write-wins — no pessimistic locking or conflict detection"). Optimistic
/// concurrency in the system applies to deployment status records, not here.
/// - Audit logging
/// </summary>
public class InstanceService
{
private readonly ITemplateEngineRepository _repository;
private readonly IAuditService _auditService;
/// <summary>
/// Initializes a new instance of the InstanceService class.
/// </summary>
/// <param name="repository">Template engine repository for data access.</param>
/// <param name="auditService">Service for audit logging.</param>
public InstanceService(ITemplateEngineRepository repository, IAuditService auditService)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_auditService = auditService ?? throw new ArgumentNullException(nameof(auditService));
}
/// <summary>
/// Creates a new instance from a template at a site.
/// </summary>
/// <param name="uniqueName">Unique name for the instance.</param>
/// <param name="templateId">ID of the template to instantiate.</param>
/// <param name="siteId">ID of the site where the instance will reside.</param>
/// <param name="areaId">Optional ID of the area to assign to the instance.</param>
/// <param name="user">Username of the user creating the instance.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result containing the created instance or failure message.</returns>
public async Task<Result<Instance>> CreateInstanceAsync(
string uniqueName,
int templateId,
int siteId,
int? areaId,
string user,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(uniqueName))
return Result<Instance>.Failure("Instance unique name is required.");
// The unique name becomes the site's Instance Actor name; a character Akka
// rejects would make ActorOf throw inside the Deployment Manager singleton on
// deploy (review 2026-10-21 01/SR-C1). Reject it here with a readable error.
var nameError = ActorNameRules.Describe(uniqueName);
if (nameError != null)
return Result<Instance>.Failure($"Invalid instance unique name: {nameError}");
// Verify template exists
var template = await _repository.GetTemplateByIdAsync(templateId, cancellationToken);
if (template == null)
return Result<Instance>.Failure($"Template with ID {templateId} not found.");
// Check for duplicate unique name
var existing = await _repository.GetInstanceByUniqueNameAsync(uniqueName, cancellationToken);
if (existing != null)
return Result<Instance>.Failure($"Instance with unique name '{uniqueName}' already exists.");
// Verify area exists if specified
if (areaId.HasValue)
{
var area = await _repository.GetAreaByIdAsync(areaId.Value, cancellationToken);
if (area == null)
return Result<Instance>.Failure($"Area with ID {areaId.Value} not found.");
if (area.SiteId != siteId)
return Result<Instance>.Failure($"Area with ID {areaId.Value} does not belong to site {siteId}.");
}
var instance = new Instance(uniqueName)
{
TemplateId = templateId,
SiteId = siteId,
AreaId = areaId,
State = InstanceState.Disabled // New instances start disabled
};
await _repository.AddInstanceAsync(instance, cancellationToken);
try { await _repository.SaveChangesAsync(cancellationToken); }
catch (InstanceNameConflictException ex) { return Result<Instance>.Failure(ex.Message); }
await _auditService.LogAsync(user, "Create", "Instance", instance.Id.ToString(),
uniqueName, instance, cancellationToken);
return Result<Instance>.Success(instance);
}
/// <summary>
/// Assigns an instance to an area.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="areaId">ID of the area to assign to, or null to clear assignment.</param>
/// <param name="user">Username of the user making the assignment.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result containing the updated instance or failure message.</returns>
public async Task<Result<Instance>> AssignToAreaAsync(
int instanceId,
int? areaId,
string user,
CancellationToken cancellationToken = default)
{
var instance = await _repository.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<Instance>.Failure($"Instance with ID {instanceId} not found.");
if (areaId.HasValue)
{
var area = await _repository.GetAreaByIdAsync(areaId.Value, cancellationToken);
if (area == null)
return Result<Instance>.Failure($"Area with ID {areaId.Value} not found.");
if (area.SiteId != instance.SiteId)
return Result<Instance>.Failure($"Area with ID {areaId.Value} does not belong to the instance's site.");
}
instance.AreaId = areaId;
await _repository.UpdateInstanceAsync(instance, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "AssignArea", "Instance", instance.Id.ToString(),
instance.UniqueName, instance, cancellationToken);
return Result<Instance>.Success(instance);
}
/// <summary>
/// Sets an attribute override for an instance. Only non-locked attributes can be overridden.
/// Cannot add or remove attributes — only override values of existing template attributes.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="attributeName">Name of the attribute to override.</param>
/// <param name="overrideValue">Override value, or null to clear.</param>
/// <param name="user">Username of the user setting the override.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result containing the attribute override or failure message.</returns>
public async Task<Result<InstanceAttributeOverride>> SetAttributeOverrideAsync(
int instanceId,
string attributeName,
string? overrideValue,
string user,
CancellationToken cancellationToken = default)
{
var instance = await _repository.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<InstanceAttributeOverride>.Failure($"Instance with ID {instanceId} not found.");
// Verify attribute exists in the template and is not locked
var templateAttrs = await _repository.GetAttributesByTemplateIdAsync(instance.TemplateId, cancellationToken);
var templateAttr = templateAttrs.FirstOrDefault(a => a.Name == attributeName);
if (templateAttr == null)
return Result<InstanceAttributeOverride>.Failure(
$"Attribute '{attributeName}' does not exist in template {instance.TemplateId}" +
OverrideNameMatching.CaseMismatchHint(attributeName, templateAttrs.Select(a => a.Name)) +
". Cannot add new attributes via overrides.");
if (templateAttr.IsLocked)
return Result<InstanceAttributeOverride>.Failure(
$"Attribute '{attributeName}' is locked and cannot be overridden.");
// Find existing override or create new one
var overrides = await _repository.GetOverridesByInstanceIdAsync(instanceId, cancellationToken);
var existingOverride = overrides.FirstOrDefault(o => o.AttributeName == attributeName);
if (existingOverride != null)
{
existingOverride.OverrideValue = overrideValue;
existingOverride.ElementDataType = templateAttr.ElementDataType;
await _repository.UpdateInstanceAttributeOverrideAsync(existingOverride, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "UpdateOverride", "InstanceAttributeOverride",
existingOverride.Id.ToString(), attributeName, existingOverride, cancellationToken);
return Result<InstanceAttributeOverride>.Success(existingOverride);
}
else
{
var newOverride = new InstanceAttributeOverride(attributeName)
{
InstanceId = instanceId,
OverrideValue = overrideValue,
ElementDataType = templateAttr.ElementDataType
};
await _repository.AddInstanceAttributeOverrideAsync(newOverride, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "CreateOverride", "InstanceAttributeOverride",
newOverride.Id.ToString(), attributeName, newOverride, cancellationToken);
return Result<InstanceAttributeOverride>.Success(newOverride);
}
}
/// <summary>
/// Sets a per-instance alarm override. The alarm must exist in the
/// instance's effective alarm set (direct, inherited, or composed) and
/// must not be locked. For HiLo alarms, the override JSON merges into the
/// inherited TriggerConfiguration setpoint-by-setpoint; for binary trigger
/// types, it replaces the whole config.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="alarmCanonicalName">Canonical name of the alarm to override.</param>
/// <param name="triggerConfigurationOverride">Override JSON for the trigger configuration.</param>
/// <param name="priorityLevelOverride">Override priority level, or null to use template value.</param>
/// <param name="user">Username of the user setting the override.</param>
/// <param name="isMesReportableOverride">Override for the alarm's MES-reportable flag, or null to use the template value.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result containing the alarm override or failure message.</returns>
public async Task<Result<InstanceAlarmOverride>> SetAlarmOverrideAsync(
int instanceId,
string alarmCanonicalName,
string? triggerConfigurationOverride,
int? priorityLevelOverride,
string user,
bool? isMesReportableOverride = null,
CancellationToken cancellationToken = default)
{
var instance = await _repository.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<InstanceAlarmOverride>.Failure($"Instance with ID {instanceId} not found.");
// Verify the alarm exists in the instance's effective alarm set and is
// not locked. The effective set is resolved via TemplateResolver so that
// composed (path-qualified) and inherited alarms are found — a lookup
// against the template's direct alarms alone would miss them, silently
// accepting an override for a non-existent name or bypassing the lock
// rule for a composed alarm. Mirrors SetAttributeOverrideAsync.
// The resolver reads member names and lock flags only, so the no-tracking,
// script-body-free analysis projection suffices (review 2026-10-21 04/P6, 08/P1).
// TPL-4: the template's analysis closure (chain + compositions) is all the resolver
// walks — not the whole template table.
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(instance.TemplateId, cancellationToken);
var resolvedAlarm = TemplateResolver
.ResolveAllMembers(instance.TemplateId, allTemplates)
.FirstOrDefault(m => m.MemberType == "Alarm" && m.CanonicalName == alarmCanonicalName);
if (resolvedAlarm == null)
return Result<InstanceAlarmOverride>.Failure(
$"Alarm '{alarmCanonicalName}' does not exist in template {instance.TemplateId}. " +
"Cannot override an unknown alarm.");
if (resolvedAlarm.IsLocked)
return Result<InstanceAlarmOverride>.Failure(
$"Alarm '{alarmCanonicalName}' is locked and cannot be overridden.");
var existingOverride = await _repository.GetAlarmOverrideAsync(
instanceId, alarmCanonicalName, cancellationToken);
if (existingOverride != null)
{
existingOverride.TriggerConfigurationOverride = triggerConfigurationOverride;
existingOverride.PriorityLevelOverride = priorityLevelOverride;
existingOverride.IsMesReportableOverride = isMesReportableOverride;
await _repository.UpdateInstanceAlarmOverrideAsync(existingOverride, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "UpdateAlarmOverride", "InstanceAlarmOverride",
existingOverride.Id.ToString(), alarmCanonicalName, existingOverride, cancellationToken);
return Result<InstanceAlarmOverride>.Success(existingOverride);
}
else
{
var newOverride = new InstanceAlarmOverride(alarmCanonicalName)
{
InstanceId = instanceId,
TriggerConfigurationOverride = triggerConfigurationOverride,
PriorityLevelOverride = priorityLevelOverride,
IsMesReportableOverride = isMesReportableOverride
};
await _repository.AddInstanceAlarmOverrideAsync(newOverride, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "CreateAlarmOverride", "InstanceAlarmOverride",
newOverride.Id.ToString(), alarmCanonicalName, newOverride, cancellationToken);
return Result<InstanceAlarmOverride>.Success(newOverride);
}
}
/// <summary>
/// Removes a per-instance alarm override. After removal the instance
/// inherits the template alarm config unchanged.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="alarmCanonicalName">Canonical name of the alarm to delete the override for.</param>
/// <param name="user">Username of the user deleting the override.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result indicating success or failure.</returns>
public async Task<Result<bool>> DeleteAlarmOverrideAsync(
int instanceId,
string alarmCanonicalName,
string user,
CancellationToken cancellationToken = default)
{
var existing = await _repository.GetAlarmOverrideAsync(
instanceId, alarmCanonicalName, cancellationToken);
if (existing == null)
return Result<bool>.Failure($"No alarm override for '{alarmCanonicalName}' on instance {instanceId}.");
await _repository.DeleteInstanceAlarmOverrideAsync(existing.Id, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "DeleteAlarmOverride", "InstanceAlarmOverride",
existing.Id.ToString(), alarmCanonicalName, existing, cancellationToken);
return Result<bool>.Success(true);
}
/// <summary>
/// Sets connection bindings for an instance in bulk.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="bindings">Connection bindings to set.</param>
/// <param name="user">Username of the user setting the bindings.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result containing the updated bindings or failure message.</returns>
public async Task<Result<IReadOnlyList<InstanceConnectionBinding>>> SetConnectionBindingsAsync(
int instanceId,
IReadOnlyList<ConnectionBinding> bindings,
string user,
CancellationToken cancellationToken = default)
{
var instance = await _repository.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<IReadOnlyList<InstanceConnectionBinding>>.Failure($"Instance with ID {instanceId} not found.");
var existingBindings = await _repository.GetBindingsByInstanceIdAsync(instanceId, cancellationToken);
var existingMap = existingBindings.ToDictionary(b => b.AttributeName, StringComparer.Ordinal);
var results = new List<InstanceConnectionBinding>();
foreach (var b in bindings)
{
if (existingMap.TryGetValue(b.AttributeName, out var existing))
{
existing.DataConnectionId = b.DataConnectionId;
existing.DataSourceReferenceOverride = b.DataSourceReferenceOverride;
await _repository.UpdateInstanceConnectionBindingAsync(existing, cancellationToken);
results.Add(existing);
}
else
{
var binding = new InstanceConnectionBinding(b.AttributeName)
{
InstanceId = instanceId,
DataConnectionId = b.DataConnectionId,
DataSourceReferenceOverride = b.DataSourceReferenceOverride
};
await _repository.AddInstanceConnectionBindingAsync(binding, cancellationToken);
results.Add(binding);
}
}
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "SetConnectionBindings", "Instance",
instance.Id.ToString(), instance.UniqueName, bindings, cancellationToken);
return Result<IReadOnlyList<InstanceConnectionBinding>>.Success(results);
}
/// <summary>
/// Enables an instance.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="user">Username of the user enabling the instance.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result containing the enabled instance or failure message.</returns>
public async Task<Result<Instance>> EnableAsync(int instanceId, string user, CancellationToken cancellationToken = default)
{
var instance = await _repository.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<Instance>.Failure($"Instance with ID {instanceId} not found.");
instance.State = InstanceState.Enabled;
await _repository.UpdateInstanceAsync(instance, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "Enable", "Instance", instance.Id.ToString(),
instance.UniqueName, instance, cancellationToken);
return Result<Instance>.Success(instance);
}
/// <summary>
/// Disables an instance.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="user">Username of the user disabling the instance.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result containing the disabled instance or failure message.</returns>
public async Task<Result<Instance>> DisableAsync(int instanceId, string user, CancellationToken cancellationToken = default)
{
var instance = await _repository.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<Instance>.Failure($"Instance with ID {instanceId} not found.");
instance.State = InstanceState.Disabled;
await _repository.UpdateInstanceAsync(instance, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "Disable", "Instance", instance.Id.ToString(),
instance.UniqueName, instance, cancellationToken);
return Result<Instance>.Success(instance);
}
/// <summary>
/// Deletes an instance.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="user">Username of the user deleting the instance.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result indicating success or failure.</returns>
public async Task<Result<bool>> DeleteAsync(int instanceId, string user, CancellationToken cancellationToken = default)
{
var instance = await _repository.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<bool>.Failure($"Instance with ID {instanceId} not found.");
await _repository.DeleteInstanceAsync(instanceId, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
await _auditService.LogAsync(user, "Delete", "Instance", instanceId.ToString(),
instance.UniqueName, null, cancellationToken);
return Result<bool>.Success(true);
}
/// <summary>
/// Gets an instance by ID.
/// </summary>
/// <param name="instanceId">ID of the instance.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The instance, or null if not found.</returns>
public async Task<Instance?> GetByIdAsync(int instanceId, CancellationToken cancellationToken = default) =>
await _repository.GetInstanceByIdAsync(instanceId, cancellationToken);
/// <summary>
/// Gets all instances for a site.
/// </summary>
/// <param name="siteId">ID of the site.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>List of instances for the site.</returns>
public async Task<IReadOnlyList<Instance>> GetBySiteIdAsync(int siteId, CancellationToken cancellationToken = default) =>
await _repository.GetInstancesBySiteIdAsync(siteId, cancellationToken);
}