From f42c17d2cee21bf28ec8373c2bba2555918605dc Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:38:41 -0500 Subject: [PATCH 1/8] fix(transport): notification-list Overwrite replaces recipients instead of appending (TRN-1, WP2 task 2.1) GetListByNameAsync now eager-loads Recipients, so the importer's Overwrite Clear() removes the target's rows before the bundle's are re-added. Fixed in the repository method (decision 2.1) so every caller gets the recipients. Regression: target {A,B} + bundle {A,C} -> {A,C}, stable on re-import. --- .../Repositories/NotificationRepository.cs | 8 +- .../Import/NotificationListOverwriteTests.cs | 173 ++++++++++++++++++ 2 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests/Import/NotificationListOverwriteTests.cs diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs index cca96c99..6d538b68 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs @@ -30,7 +30,13 @@ public class NotificationRepository : INotificationRepository /// public async Task GetListByNameAsync(string name, CancellationToken cancellationToken = default) - => await _context.Set().FirstOrDefaultAsync(l => l.Name == name, cancellationToken); + // Eager-load Recipients (TRN-1): the Transport importer's Overwrite clears and + // re-adds the recipient collection. Without the Include the Clear() ran on an + // unloaded collection, deleted nothing, and the bundle's recipients were appended + // to the target's — duplicates plus recipients the source had removed. + => await _context.Set() + .Include(n => n.Recipients) + .FirstOrDefaultAsync(l => l.Name == name, cancellationToken); /// public async Task AddNotificationListAsync(NotificationList list, CancellationToken cancellationToken = default) diff --git a/tests/ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests/Import/NotificationListOverwriteTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests/Import/NotificationListOverwriteTests.cs new file mode 100644 index 00000000..51da6c0e --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests/Import/NotificationListOverwriteTests.cs @@ -0,0 +1,173 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates; + +namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import; + +/// +/// TRN-1 (WP2 task 2.1): a notification-list Overwrite must REPLACE the target's +/// recipients with the bundle's. GetListByNameAsync used to load the list +/// without its recipients, so the apply's Recipients.Clear() ran on an +/// unloaded collection, deleted nothing, and the bundle's recipients were appended +/// on top — duplicating shared recipients and keeping removed ones, with another +/// copy added on every re-import. +/// +public sealed class NotificationListOverwriteTests : IDisposable +{ + private readonly ServiceProvider _provider; + + /// Builds an in-memory configuration database plus the Transport services. + public NotificationListOverwriteTests() + { + var services = new ServiceCollection(); + services.AddSingleton(new ConfigurationBuilder().AddInMemoryCollection().Build()); + var dbName = $"NotificationListOverwriteTests_{Guid.NewGuid()}"; + services.AddDbContext(opts => opts + .UseInMemoryDatabase(dbName) + .ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddTransport(); + _provider = services.BuildServiceProvider(); + } + + /// Releases the resources held by this instance. + public void Dispose() => _provider.Dispose(); + + /// + /// Target {A,B} + bundle {A,C} must end as exactly {A,C}, and a second + /// Overwrite import of the same bundle must leave it at {A,C}. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Overwrite_replaces_recipients_and_is_idempotent_on_reimport() + { + // Source state the bundle captures: {A, C}. + await using (var scope = _provider.CreateAsyncScope()) + { + var ctx = scope.ServiceProvider.GetRequiredService(); + var list = new NotificationList("Ops"); + list.Recipients.Add(NotificationRecipient.ForEmail("A", "a@example.com")); + list.Recipients.Add(NotificationRecipient.ForEmail("C", "c@example.com")); + ctx.NotificationLists.Add(list); + await ctx.SaveChangesAsync(); + } + + var bundle = await ExportAsync(); + + // Turn the database into the target state: {A, B}. + await using (var scope = _provider.CreateAsyncScope()) + { + var ctx = scope.ServiceProvider.GetRequiredService(); + var list = await ctx.NotificationLists.Include(l => l.Recipients).SingleAsync(l => l.Name == "Ops"); + var c = list.Recipients.Single(r => r.Name == "C"); + list.Recipients.Remove(c); + ctx.Remove(c); + list.Recipients.Add(NotificationRecipient.ForEmail("B", "b@example.com")); + await ctx.SaveChangesAsync(); + } + Assert.Equal(new[] { "A", "B" }, await RecipientNamesAsync()); + + await ImportOverwriteAsync(bundle); + Assert.Equal(new[] { "A", "C" }, await RecipientNamesAsync()); + + // Re-import the same bundle: still exactly {A, C}, no extra copies. + await ImportOverwriteAsync(bundle); + Assert.Equal(new[] { "A", "C" }, await RecipientNamesAsync()); + } + + /// + /// The repository method itself must return the list with its recipients — every + /// caller (importer, delivery adapters) relies on the navigation being populated. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task GetListByNameAsync_loads_recipients() + { + await using (var scope = _provider.CreateAsyncScope()) + { + var ctx = scope.ServiceProvider.GetRequiredService(); + var list = new NotificationList("Ops"); + list.Recipients.Add(NotificationRecipient.ForEmail("A", "a@example.com")); + ctx.NotificationLists.Add(list); + await ctx.SaveChangesAsync(); + } + + await using (var scope = _provider.CreateAsyncScope()) + { + var repo = scope.ServiceProvider.GetRequiredService(); + var loaded = await repo.GetListByNameAsync("Ops"); + Assert.NotNull(loaded); + Assert.Single(loaded!.Recipients); + } + } + + private async Task ExportAsync() + { + await using var scope = _provider.CreateAsyncScope(); + var exporter = scope.ServiceProvider.GetRequiredService(); + var ctx = scope.ServiceProvider.GetRequiredService(); + var listIds = await ctx.NotificationLists.Select(l => l.Id).ToListAsync(); + var selection = new ExportSelection( + TemplateIds: Array.Empty(), + SharedScriptIds: Array.Empty(), + ExternalSystemIds: Array.Empty(), + DatabaseConnectionIds: Array.Empty(), + NotificationListIds: listIds, + SmtpConfigurationIds: Array.Empty(), + ApiMethodIds: Array.Empty(), + IncludeDependencies: false); + var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev", + passphrase: null, cancellationToken: CancellationToken.None); + using var ms = new MemoryStream(); + await stream.CopyToAsync(ms); + return ms.ToArray(); + } + + private async Task ImportOverwriteAsync(byte[] bundle) + { + Guid sessionId; + await using (var scope = _provider.CreateAsyncScope()) + { + var importer = scope.ServiceProvider.GetRequiredService(); + using var input = new MemoryStream(bundle, writable: false); + sessionId = (await importer.LoadAsync(input, passphrase: null)).SessionId; + } + + await using (var scope = _provider.CreateAsyncScope()) + { + var importer = scope.ServiceProvider.GetRequiredService(); + var result = await importer.ApplyAsync(sessionId, + new List { new("NotificationList", "Ops", ResolutionAction.Overwrite, null) }, + user: "bob"); + Assert.Equal(1, result.Overwritten); + } + } + + private async Task RecipientNamesAsync() + { + await using var scope = _provider.CreateAsyncScope(); + var ctx = scope.ServiceProvider.GetRequiredService(); + return await ctx.NotificationRecipients + .Where(r => r.NotificationListId == ctx.NotificationLists.Single(l => l.Name == "Ops").Id) + .OrderBy(r => r.Name) + .Select(r => r.Name) + .ToArrayAsync(); + } +} From c207809ef398a770230093b769b4dfaf953da757 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:43:00 -0500 Subject: [PATCH 2/8] fix(transport): range-check the manifest KDF iteration count before deriving the key (TRN-10, WP2 task 2.7) BundleSecretEncryptor.Decrypt now refuses an iteration count outside [MinPbkdf2Iterations, MaxPbkdf2Iterations] before PBKDF2 runs. The manifest JSON path was already guarded by the EncryptionMetadata constructor (pinned by a new test), but a record 'with' (or any non-ctor path) bypassed it and derived with int.MaxValue iterations; the encryptor no longer relies on it. --- .../Encryption/BundleSecretEncryptor.cs | 13 ++++++ .../Encryption/BundleSecretEncryptorTests.cs | 42 +++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/ZB.MOM.WW.ScadaBridge.Transport/Encryption/BundleSecretEncryptor.cs b/src/ZB.MOM.WW.ScadaBridge.Transport/Encryption/BundleSecretEncryptor.cs index ec5fcfd5..7c515a12 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Transport/Encryption/BundleSecretEncryptor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Transport/Encryption/BundleSecretEncryptor.cs @@ -83,6 +83,19 @@ public sealed class BundleSecretEncryptor throw new CryptographicException("Unsupported bundle encryption parameters."); } + // TRN-10: the iteration count comes from the uploaded (untrusted) manifest. + // EncryptionMetadata's constructor range-checks it, but a record `with` + // expression or any other non-constructor path bypasses that, so re-check + // here — before PBKDF2 runs — or a hostile bundle declaring int.MaxValue + // pins a thread (and the single-flight transport gate) for tens of minutes. + if (metadata.Iterations < EncryptionMetadata.MinPbkdf2Iterations + || metadata.Iterations > EncryptionMetadata.MaxPbkdf2Iterations) + { + throw new CryptographicException( + $"Bundle key-derivation iteration count {metadata.Iterations} is outside the supported range " + + $"[{EncryptionMetadata.MinPbkdf2Iterations}, {EncryptionMetadata.MaxPbkdf2Iterations}]."); + } + var salt = Convert.FromBase64String(metadata.SaltB64); var nonce = Convert.FromBase64String(metadata.IvB64); var key = DeriveKey(passphrase, salt, metadata.Iterations); diff --git a/tests/ZB.MOM.WW.ScadaBridge.Transport.Tests/Encryption/BundleSecretEncryptorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Transport.Tests/Encryption/BundleSecretEncryptorTests.cs index c643fade..b519b065 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Transport.Tests/Encryption/BundleSecretEncryptorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Transport.Tests/Encryption/BundleSecretEncryptorTests.cs @@ -118,3 +118,45 @@ public sealed class BundleSecretEncryptorTests Assert.Equal(plaintext, recovered); } } + +/// +/// TRN-10 (WP2 task 2.7): the PBKDF2 iteration count read from an uploaded manifest +/// must be range-checked before the key is derived, so a hostile bundle cannot pin a +/// thread (and the single-flight transport gate) with an absurd count. +/// +public sealed class BundleSecretEncryptorIterationBoundTests +{ + private static EncryptionMetadata ValidMetadata() => + new("AES-256-GCM", "PBKDF2-SHA256", EncryptionMetadata.MinPbkdf2Iterations, + Convert.ToBase64String(new byte[16]), Convert.ToBase64String(new byte[12])); + + /// A metadata record whose iteration count was set past the ceiling is refused before PBKDF2 runs. + [Theory] + [InlineData(int.MaxValue)] + [InlineData(EncryptionMetadata.MaxPbkdf2Iterations + 1)] + [InlineData(EncryptionMetadata.MinPbkdf2Iterations - 1)] + [InlineData(0)] + [InlineData(-1)] + public void Decrypt_rejects_out_of_range_iterations_without_deriving(int iterations) + { + // `with` bypasses the record constructor's range check — the encryptor must + // not rely on it. + var metadata = ValidMetadata() with { Iterations = iterations }; + var sw = System.Diagnostics.Stopwatch.StartNew(); + Assert.ThrowsAny(() => + new BundleSecretEncryptor().Decrypt(new byte[32], metadata, "pass")); + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(5), "the key must not be derived first"); + } + + /// A manifest JSON carrying an absurd iteration count does not yield a usable metadata record. + [Fact] + public void Manifest_with_absurd_iterations_is_rejected_on_read() + { + var json = """ + {"algorithm":"AES-256-GCM","kdf":"PBKDF2-SHA256","iterations":2147483647,"saltB64":"","ivB64":""} + """; + Assert.ThrowsAny(() => + System.Text.Json.JsonSerializer.Deserialize( + json, ZB.MOM.WW.ScadaBridge.Transport.Serialization.BundleJsonOptions.Default)); + } +} From 61c6278bd025c35b4b0ea9ce00436b86d973b29d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:48:00 -0500 Subject: [PATCH 3/8] fix(cli): site/data-connection/api-method update are preserve-if-null partial updates (CLI-2, WP2 task 2.8) Decision 2.8: preserve-if-null on the server. UpdateSiteCommand, UpdateDataConnectionCommand and UpdateApiMethodCommand fields (except the id) are now nullable; the ManagementActor handlers apply only non-null values and treat an empty string as 'clear this optional field'. The CLI update commands no longer require --name/--protocol/--script and drop the --failover-retry-count (3) and --timeout (30) defaults, so an omitted option travels as null instead of overwriting the stored value (site update --name used to null both gRPC addresses). The site gRPC-address validation now runs on the merged values. Additive/compatible: the fields only became nullable, so an older CLI that always sends every field still deserializes (pinned by a test) and now simply updates every field as before. The Central UI full-entity forms send "" for a field the operator cleared (description/addresses, removed backup endpoint, cleared parameter/return definitions) so clearing keeps working. --- docs/requirements/Component-CLI.md | 6 +- .../Commands/ApiMethodCommands.cs | 28 ++- .../Commands/DataConnectionCommands.cs | 31 ++- .../Commands/SiteCommands.cs | 31 ++- src/ZB.MOM.WW.ScadaBridge.CLI/README.md | 47 ++-- .../Components/Pages/Admin/SiteForm.razor | 7 +- .../Pages/Design/ApiMethodForm.razor | 3 +- .../Pages/Design/DataConnectionForm.razor | 3 +- .../Management/DataConnectionCommands.cs | 7 +- .../Messages/Management/InboundApiCommands.cs | 7 +- .../Messages/Management/SiteCommands.cs | 7 +- .../ManagementActor.cs | 69 ++++-- .../PartialUpdate.cs | 19 ++ .../PartialUpdateCommandTests.cs | 98 ++++++++ .../UpdateCommandContractTests.cs | 46 +++- .../Audit/FlowDebuggerDrillinTests.cs | 2 +- .../PartialUpdateHandlerTests.cs | 215 ++++++++++++++++++ 17 files changed, 533 insertions(+), 93 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/PartialUpdateCommandTests.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/PartialUpdateHandlerTests.cs diff --git a/docs/requirements/Component-CLI.md b/docs/requirements/Component-CLI.md index 0a07e74f..c22023d6 100644 --- a/docs/requirements/Component-CLI.md +++ b/docs/requirements/Component-CLI.md @@ -171,6 +171,8 @@ scadabridge site area delete --id scadabridge site deploy-artifacts [--site-id ] ``` +`site update`, `data-connection update` and `api-method update` are **partial** updates (CLI-2, 2026-12-03): only the options passed are sent; an omitted option travels as null and the server keeps the stored value (preserve-if-null in the `ManagementActor` handler), and an empty string (`""`) clears an optional field. Previously every omitted option was sent as null or a default (`--failover-retry-count` 3, `--timeout` 30) and overwrote the stored value — `site update --id 3 --name X` nulled both gRPC addresses. An older CLI that always sends every field still deserializes unchanged. + ### Deployment Commands ``` scadabridge deploy instance --id @@ -185,7 +187,7 @@ scadabridge deploy status [--instance-id ] [--status ] [--page ] scadabridge data-connection list [--site-id ] scadabridge data-connection get --id scadabridge data-connection create --site-id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] -scadabridge data-connection update --id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] +scadabridge data-connection update --id [--name ] [--protocol ] [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] scadabridge data-connection delete --id scadabridge data-connection move --id --site-id ``` @@ -423,7 +425,7 @@ scadabridge db-connection delete --id scadabridge api-method list scadabridge api-method get --id scadabridge api-method create --name --script [--timeout ] [--parameters ] [--return-def ] -scadabridge api-method update --id --script [--timeout ] [--parameters ] [--return-def ] +scadabridge api-method update --id [--script ] [--timeout ] [--parameters ] [--return-def ] scadabridge api-method delete --id scadabridge api-method validate --id scadabridge api-method recompile --id diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs index 546075e6..3ef8dbcf 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs @@ -123,21 +123,27 @@ public static class ApiMethodCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "API method ID", Required = true }; - var scriptOption = new Option("--script") { Description = "Script code", Required = true }; - var timeoutOption = new Option("--timeout") { Description = "Timeout in seconds" }; - timeoutOption.DefaultValueFactory = _ => 30; - var parametersOption = new Option("--parameters") { Description = "Parameter definitions JSON" }; - var returnDefOption = new Option("--return-def") { Description = "Return type definition" }; + var scriptOption = new Option("--script") { Description = "Script code (omitted = unchanged)" }; + var timeoutOption = new Option("--timeout") { Description = "Timeout in seconds (omitted = unchanged)" }; + var parametersOption = new Option("--parameters") { Description = "Parameter definitions JSON (omitted = unchanged; \"\" clears)" }; + var returnDefOption = new Option("--return-def") { Description = "Return type definition (omitted = unchanged; \"\" clears)" }; // bool? so an update that omits the flag leaves the stored value unchanged. var traceAllCallsOption = new Option("--trace-all-calls") { Description = "Trace every production call to this method for the Flow Debugger (true/false; omitted = unchanged; adds 7-10 audit rows per call)" }; - var cmd = new Command("update") { Description = "Update an API method" }; + var cmd = new Command("update") { Description = "Update an API method (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(scriptOption); cmd.Add(timeoutOption); @@ -147,14 +153,16 @@ public static class ApiMethodCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var script = result.GetValue(scriptOption)!; + var script = result.GetValue(scriptOption); var timeout = result.GetValue(timeoutOption); var parameters = result.GetValue(parametersOption); var returnDef = result.GetValue(returnDefOption); var traceAllCalls = result.GetValue(traceAllCallsOption); + var command = new UpdateApiMethodCommand(id, script, timeout, parameters, returnDef, traceAllCalls); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateApiMethodCommand(id, script, timeout, parameters, returnDef, traceAllCalls)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs index 4a06dd19..8839b319 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs @@ -58,18 +58,25 @@ public static class DataConnectionCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "Data connection ID", Required = true }; - var nameOption = new Option("--name") { Description = "Connection name", Required = true }; - var protocolOption = new Option("--protocol") { Description = "Protocol", Required = true }; - var configOption = new Option("--primary-config", "--configuration") { Description = "Primary configuration JSON" }; - var backupConfigOption = new Option("--backup-config") { Description = "Backup configuration JSON" }; + var nameOption = new Option("--name") { Description = "Connection name (omitted = unchanged)" }; + var protocolOption = new Option("--protocol") { Description = "Protocol (omitted = unchanged)" }; + var configOption = new Option("--primary-config", "--configuration") { Description = "Primary configuration JSON (omitted = unchanged)" }; + var backupConfigOption = new Option("--backup-config") { Description = "Backup configuration JSON (omitted = unchanged; \"\" removes the backup)" }; var configFileOption = ValueSourceOptions.CreateFileOption(configOption, "the primary configuration JSON"); var backupConfigFileOption = ValueSourceOptions.CreateFileOption(backupConfigOption, "the backup configuration JSON"); - var failoverRetryOption = new Option("--failover-retry-count") { Description = "Number of retries before failover to backup", DefaultValueFactory = _ => 3 }; + var failoverRetryOption = new Option("--failover-retry-count") { Description = "Number of retries before failover to backup (omitted = unchanged)" }; - var cmd = new Command("update") { Description = "Update a data connection" }; + var cmd = new Command("update") { Description = "Update a data connection (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(nameOption); cmd.Add(protocolOption); @@ -80,14 +87,16 @@ public static class DataConnectionCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var name = result.GetValue(nameOption)!; - var protocol = result.GetValue(protocolOption)!; + var name = result.GetValue(nameOption); + var protocol = result.GetValue(protocolOption); var config = ValueSourceOptions.GetValue(result, configOption, configFileOption); var backupConfig = ValueSourceOptions.GetValue(result, backupConfigOption, backupConfigFileOption); var failoverRetryCount = result.GetValue(failoverRetryOption); + var command = new UpdateDataConnectionCommand(id, name, protocol, config, backupConfig, failoverRetryCount); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateDataConnectionCommand(id, name, protocol, config, backupConfig, failoverRetryCount)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs index 6c0a900f..efd76b5d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs @@ -88,17 +88,24 @@ public static class SiteCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "Site ID", Required = true }; - var nameOption = new Option("--name") { Description = "Site name", Required = true }; - var descOption = new Option("--description") { Description = "Site description" }; - var nodeAOption = new Option("--node-a-address") { Description = "Akka address for Node A" }; - var nodeBOption = new Option("--node-b-address") { Description = "Akka address for Node B" }; - var grpcNodeAOption = new Option("--grpc-node-a-address") { Description = "gRPC address for Node A" }; - var grpcNodeBOption = new Option("--grpc-node-b-address") { Description = "gRPC address for Node B" }; + var nameOption = new Option("--name") { Description = "Site name (omitted = unchanged)" }; + var descOption = new Option("--description") { Description = "Site description (omitted = unchanged; \"\" clears)" }; + var nodeAOption = new Option("--node-a-address") { Description = "Akka address for Node A (omitted = unchanged; \"\" clears)" }; + var nodeBOption = new Option("--node-b-address") { Description = "Akka address for Node B (omitted = unchanged; \"\" clears)" }; + var grpcNodeAOption = new Option("--grpc-node-a-address") { Description = "gRPC address for Node A (omitted = unchanged; \"\" clears)" }; + var grpcNodeBOption = new Option("--grpc-node-b-address") { Description = "gRPC address for Node B (omitted = unchanged; \"\" clears)" }; - var cmd = new Command("update") { Description = "Update an existing site" }; + var cmd = new Command("update") { Description = "Update an existing site (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(nameOption); cmd.Add(descOption); @@ -109,15 +116,17 @@ public static class SiteCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var name = result.GetValue(nameOption)!; + var name = result.GetValue(nameOption); var desc = result.GetValue(descOption); var nodeA = result.GetValue(nodeAOption); var nodeB = result.GetValue(nodeBOption); var grpcNodeA = result.GetValue(grpcNodeAOption); var grpcNodeB = result.GetValue(grpcNodeBOption); + var command = new UpdateSiteCommand(id, name, desc, nodeA, nodeB, grpcNodeA, grpcNodeB); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateSiteCommand(id, name, desc, nodeA, nodeB, grpcNodeA, grpcNodeB)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md index 73e2fa41..01388f3c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md @@ -976,22 +976,21 @@ scadabridge --url site create --name --identifier [--des #### `site update` -Update an existing site. An update **replaces** the whole entity — every required field -below must be supplied with its post-update value, even if unchanged. +Update an existing site. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url site update --id --name [--description ] [--node-a-address ] [--node-b-address ] [--grpc-node-a-address ] [--grpc-node-b-address ] +scadabridge --url site update --id [--name ] [--description ] [--node-a-address ] [--node-b-address ] [--grpc-node-a-address ] [--grpc-node-b-address ] ``` | Option | Required | Description | |--------|----------|-------------| | `--id` | yes | Site ID | -| `--name` | yes | Human-readable site name | -| `--description` | no | Site description | -| `--node-a-address` | no | Akka.NET cluster address for Node A | -| `--node-b-address` | no | Akka.NET cluster address for Node B | -| `--grpc-node-a-address` | no | gRPC streaming address for Node A | -| `--grpc-node-b-address` | no | gRPC streaming address for Node B | +| `--name` | no | Human-readable site name (omitted = unchanged) | +| `--description` | no | Site description (omitted = unchanged; `""` clears) | +| `--node-a-address` | no | Akka.NET cluster address for Node A (omitted = unchanged; `""` clears) | +| `--node-b-address` | no | Akka.NET cluster address for Node B (omitted = unchanged; `""` clears) | +| `--grpc-node-a-address` | no | gRPC streaming address for Node A (omitted = unchanged; `""` clears) | +| `--grpc-node-b-address` | no | gRPC streaming address for Node B (omitted = unchanged; `""` clears) | #### `site delete` @@ -1263,23 +1262,22 @@ scadabridge --url data-connection create --site-id --name - #### `data-connection update` -Update a data connection definition. An update **replaces** the whole entity — every -required field below must be supplied, even if unchanged. +Update a data connection definition. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url data-connection update --id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] +scadabridge --url data-connection update --id [--name ] [--protocol ] [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] ``` | Option | Required | Description | |--------|----------|-------------| | `--id` | yes | Data connection ID | -| `--name` | yes | Connection name | -| `--protocol` | yes | Protocol identifier | -| `--primary-config` | no | Primary protocol-specific configuration as a JSON string (alias `--configuration`) | +| `--name` | no | Connection name (omitted = unchanged) | +| `--protocol` | no | Protocol identifier (omitted = unchanged) | +| `--primary-config` | no | Primary protocol-specific configuration as a JSON string (alias `--configuration`; omitted = unchanged) | | `--primary-config-file` | no | Read the primary configuration from a file, or stdin with `-` — use it when the config carries a secret (MxGateway `apiKey`, OPC UA password). Not together with `--primary-config`. | -| `--backup-config` | no | Backup protocol-specific configuration as a JSON string | +| `--backup-config` | no | Backup protocol-specific configuration as a JSON string (omitted = unchanged; `""` removes the backup) | | `--backup-config-file` | no | Read the backup configuration from a file, or stdin with `-`. Not together with `--backup-config`. | -| `--failover-retry-count` | no | Retries before failover to the backup configuration (default: `3`) | +| `--failover-retry-count` | no | Retries before failover to the backup configuration (omitted = unchanged) | #### `data-connection move` @@ -2497,21 +2495,20 @@ scadabridge --url api-method create --name --script [--t #### `api-method update` -Update an inbound API method. An update **replaces** the whole entity — every required -field below must be supplied, even if unchanged. +Update an inbound API method. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url api-method update --id --script [--timeout ] [--parameters ] [--return-def ] [--trace-all-calls ] +scadabridge --url api-method update --id [--script ] [--timeout ] [--parameters ] [--return-def ] [--trace-all-calls ] ``` | Option | Required | Default | Description | |--------|----------|---------|-------------| | `--id` | yes | — | API method ID | -| `--script` | yes | — | Script source code implementing the method | -| `--timeout` | no | `30` | Timeout in seconds | -| `--parameters` | no | — | Parameter definitions JSON | -| `--return-def` | no | — | Return type definition JSON | -| `--trace-all-calls` | no | unchanged | `true`/`false` — trace every production call for the Flow Debugger. **Adds 7–10 audit rows per call** (3 of them trace-only). Omitted = the stored value is left as-is (the one field the replace-all rule does not apply to) | +| `--script` | no | unchanged | Script source code implementing the method | +| `--timeout` | no | unchanged | Timeout in seconds | +| `--parameters` | no | unchanged | Parameter definitions JSON (`""` clears) | +| `--return-def` | no | unchanged | Return type definition JSON (`""` clears) | +| `--trace-all-calls` | no | unchanged | `true`/`false` — trace every production call for the Flow Debugger. **Adds 7–10 audit rows per call** (3 of them trace-only) | Script changes take effect immediately — the updated code is recompiled in-memory on the active central node. No restart is required. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor index 9c325214..11d3b548 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor @@ -168,8 +168,11 @@ return; } await MutationServices.ExecuteConfigurationAsync(_editingSite is not null - ? new UpdateSiteCommand(_editingSite.Id, _formName.Trim(), _formDescription?.Trim(), - _formNodeAAddress?.Trim(), _formNodeBAddress?.Trim(), _formGrpcNodeAAddress?.Trim(), _formGrpcNodeBAddress?.Trim()) + // Update is preserve-if-null (CLI-2): this full-entity form sends "" for a + // field the operator cleared so the server clears it rather than keeping it. + ? new UpdateSiteCommand(_editingSite.Id, _formName.Trim(), _formDescription?.Trim() ?? "", + _formNodeAAddress?.Trim() ?? "", _formNodeBAddress?.Trim() ?? "", + _formGrpcNodeAAddress?.Trim() ?? "", _formGrpcNodeBAddress?.Trim() ?? "") : new CreateSiteCommand(_formName.Trim(), _formIdentifier.Trim(), _formDescription?.Trim(), _formNodeAAddress?.Trim(), _formNodeBAddress?.Trim(), _formGrpcNodeAAddress?.Trim(), _formGrpcNodeBAddress?.Trim())); CommunicationService.RefreshSiteAddresses(); diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor index e36eddfd..d68ddd86 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor @@ -399,7 +399,8 @@ { var methodName = _existing?.Name ?? _name.Trim(); await MutationServices.ExecuteConfigurationAsync(_existing is not null - ? new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls) + // Update is preserve-if-null (CLI-2): "" clears a removed definition. + ? new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim() ?? "", _returns?.Trim() ?? "", _traceAllCalls) : new CreateApiMethodCommand(methodName, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)); // Reconcile per-key method-scopes for the affected keys (added/removed vs. load time). diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor index 6f40918e..913839ab 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor @@ -382,7 +382,8 @@ try { await MutationServices.ExecuteConfigurationAsync(_editingConnection is not null - ? new UpdateDataConnectionCommand(_editingConnection.Id, _formName.Trim(), _protocol, primaryJson, backupJson, _showBackup ? _formFailoverRetryCount : 3) + // Update is preserve-if-null (CLI-2): "" clears a removed backup endpoint. + ? new UpdateDataConnectionCommand(_editingConnection.Id, _formName.Trim(), _protocol, primaryJson, backupJson ?? "", _showBackup ? _formFailoverRetryCount : 3) : new CreateDataConnectionCommand(_formSiteId, _formName.Trim(), _protocol, primaryJson, backupJson, _showBackup ? _formFailoverRetryCount : 3)); NavigationManager.NavigateTo("/design/connections"); } diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs index 08881df9..0fd06067 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs @@ -3,7 +3,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; public record ListDataConnectionsCommand(int? SiteId = null); public record GetDataConnectionCommand(int DataConnectionId); public record CreateDataConnectionCommand(int SiteId, string Name, string Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int FailoverRetryCount = 3); -public record UpdateDataConnectionCommand(int DataConnectionId, string Name, string Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int FailoverRetryCount = 3); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// +public record UpdateDataConnectionCommand(int DataConnectionId, string? Name, string? Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int? FailoverRetryCount = null); public record DeleteDataConnectionCommand(int DataConnectionId); /// diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs index 1119f586..63435f79 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs @@ -4,8 +4,13 @@ public record ListApiMethodsCommand; public record GetApiMethodCommand(int ApiMethodId); /// Flow Debugger (design 2026-09-05 §5.2): trace every production call to this method. Additive; defaults to off. public record CreateApiMethodCommand(string Name, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool TraceAllCalls = false); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// /// Flow Debugger (design 2026-09-05 §5.2): null leaves the stored value unchanged so an older CLI never resets it. -public record UpdateApiMethodCommand(int ApiMethodId, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool? TraceAllCalls = null); +public record UpdateApiMethodCommand(int ApiMethodId, string? Script, int? TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool? TraceAllCalls = null); public record DeleteApiMethodCommand(int ApiMethodId); /// /// Compiles the method's stored script on the receiving central node and returns the diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs index 4fac1070..284c73f5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs @@ -3,7 +3,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; public record ListSitesCommand; public record GetSiteCommand(int SiteId); public record CreateSiteCommand(string Name, string SiteIdentifier, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); -public record UpdateSiteCommand(int SiteId, string Name, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// +public record UpdateSiteCommand(int SiteId, string? Name, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); public record DeleteSiteCommand(int SiteId); public record ListAreasCommand(int SiteId); public record CreateAreaCommand(int SiteId, string Name, int? ParentAreaId); diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index 923e6e47..951c65b0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -2062,16 +2062,25 @@ public class ManagementActor : ReceiveActor private static async Task HandleUpdateSite(IServiceProvider sp, UpdateSiteCommand cmd, string user) { - ValidateSiteGrpcAddresses(cmd.GrpcNodeAAddress, cmd.GrpcNodeBAddress); var repo = sp.GetRequiredService(); var site = await repo.GetSiteByIdAsync(cmd.SiteId) ?? throw new ManagementCommandException($"Site with ID {cmd.SiteId} not found."); - site.Name = cmd.Name; - site.Description = cmd.Description; - site.NodeAAddress = cmd.NodeAAddress; - site.NodeBAddress = cmd.NodeBAddress; - site.GrpcNodeAAddress = cmd.GrpcNodeAAddress; - site.GrpcNodeBAddress = cmd.GrpcNodeBAddress; + // CLI-2: preserve-if-null partial update. Validate the EFFECTIVE addresses + // (the merge of the command and the stored row) before anything is written. + var grpcNodeA = PartialUpdate.Optional(cmd.GrpcNodeAAddress, site.GrpcNodeAAddress); + var grpcNodeB = PartialUpdate.Optional(cmd.GrpcNodeBAddress, site.GrpcNodeBAddress); + ValidateSiteGrpcAddresses(grpcNodeA, grpcNodeB); + if (cmd.Name is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Name)) + throw new ManagementCommandException("Site name must not be empty."); + site.Name = cmd.Name; + } + site.Description = PartialUpdate.Optional(cmd.Description, site.Description); + site.NodeAAddress = PartialUpdate.Optional(cmd.NodeAAddress, site.NodeAAddress); + site.NodeBAddress = PartialUpdate.Optional(cmd.NodeBAddress, site.NodeBAddress); + site.GrpcNodeAAddress = grpcNodeA; + site.GrpcNodeBAddress = grpcNodeB; await repo.UpdateSiteAsync(site); await repo.SaveChangesAsync(); var commService = sp.GetService(); @@ -2234,14 +2243,33 @@ public class ManagementActor : ReceiveActor var repo = sp.GetRequiredService(); var conn = await repo.GetDataConnectionByIdAsync(cmd.DataConnectionId) ?? throw new ManagementCommandException($"DataConnection with ID {cmd.DataConnectionId} not found."); - conn.Name = cmd.Name; - conn.Protocol = cmd.Protocol; + // CLI-2: preserve-if-null partial update — an omitted field keeps the stored + // value; an empty string clears an optional configuration. + if (cmd.Name is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Name)) + throw new ManagementCommandException("Data connection name must not be empty."); + conn.Name = cmd.Name; + } + if (cmd.Protocol is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Protocol)) + throw new ManagementCommandException("Data connection protocol must not be empty."); + conn.Protocol = cmd.Protocol; + } // Sentinel-preserving merge: a client that round-trips a scrubbed config // (secrets replaced with the redaction sentinel) keeps the stored secret // rather than wiping it. Non-sentinel values overwrite as usual. - conn.PrimaryConfiguration = ConfigSecretScrubber.MergeSentinels(cmd.PrimaryConfiguration, conn.PrimaryConfiguration); - conn.BackupConfiguration = ConfigSecretScrubber.MergeSentinels(cmd.BackupConfiguration, conn.BackupConfiguration); - conn.FailoverRetryCount = cmd.FailoverRetryCount; + if (cmd.PrimaryConfiguration is not null) + conn.PrimaryConfiguration = string.IsNullOrWhiteSpace(cmd.PrimaryConfiguration) + ? null + : ConfigSecretScrubber.MergeSentinels(cmd.PrimaryConfiguration, conn.PrimaryConfiguration); + if (cmd.BackupConfiguration is not null) + conn.BackupConfiguration = string.IsNullOrWhiteSpace(cmd.BackupConfiguration) + ? null + : ConfigSecretScrubber.MergeSentinels(cmd.BackupConfiguration, conn.BackupConfiguration); + if (cmd.FailoverRetryCount is { } failoverRetryCount) + conn.FailoverRetryCount = failoverRetryCount; await repo.UpdateDataConnectionAsync(conn); await repo.SaveChangesAsync(); var publicShape = DataConnectionPublicShape(conn); @@ -3975,10 +4003,19 @@ public class ManagementActor : ReceiveActor var repo = sp.GetRequiredService(); var method = await repo.GetApiMethodByIdAsync(cmd.ApiMethodId) ?? throw new ManagementCommandException($"ApiMethod with ID {cmd.ApiMethodId} not found."); - method.Script = cmd.Script; - method.TimeoutSeconds = cmd.TimeoutSeconds; - method.ParameterDefinitions = cmd.ParameterDefinitions; - method.ReturnDefinition = cmd.ReturnDefinition; + // CLI-2: preserve-if-null partial update — an omitted field keeps the stored + // value (an omitted --timeout used to reset it to 30 and drop both + // definitions); an empty string clears an optional definition. + if (cmd.Script is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Script)) + throw new ManagementCommandException("API method script must not be empty."); + method.Script = cmd.Script; + } + if (cmd.TimeoutSeconds is { } timeoutSeconds) + method.TimeoutSeconds = timeoutSeconds; + method.ParameterDefinitions = PartialUpdate.Optional(cmd.ParameterDefinitions, method.ParameterDefinitions); + method.ReturnDefinition = PartialUpdate.Optional(cmd.ReturnDefinition, method.ReturnDefinition); if (cmd.TraceAllCalls is { } traceAllCalls) method.TraceAllCalls = traceAllCalls; await repo.UpdateApiMethodAsync(method); diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs new file mode 100644 index 00000000..c317a242 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs @@ -0,0 +1,19 @@ +namespace ZB.MOM.WW.ScadaBridge.ManagementService; + +/// +/// Preserve-if-null merge rules for the partial update commands (CLI-2): +/// UpdateSiteCommand, UpdateDataConnectionCommand and +/// UpdateApiMethodCommand. A null field means "not supplied — keep the +/// stored value"; an empty (or whitespace-only) string means "clear this optional +/// field". The CLI sends only the options that were actually passed, and the Central +/// UI's full-entity forms send an empty string for a field the operator cleared. +/// +internal static class PartialUpdate +{ + /// Merges an optional (nullable) string field. + /// The value carried by the command, or null when not supplied. + /// The value currently stored. + /// when is null; null when it is blank; otherwise . + public static string? Optional(string? incoming, string? stored) => + incoming is null ? stored : string.IsNullOrWhiteSpace(incoming) ? null : incoming; +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/PartialUpdateCommandTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/PartialUpdateCommandTests.cs new file mode 100644 index 00000000..7f24715c --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/PartialUpdateCommandTests.cs @@ -0,0 +1,98 @@ +using System.CommandLine; +using ZB.MOM.WW.ScadaBridge.CLI.Commands; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; + +namespace ZB.MOM.WW.ScadaBridge.CLI.Tests; + +/// +/// CLI-2 (WP2 task 2.8): site update, data-connection update and +/// api-method update send only the options actually passed. Before the fix an +/// omitted option was sent as null (or as a default: --failover-retry-count 3, +/// --timeout 30) and the server overwrote the stored value — e.g. +/// site update --id 3 --name X nulled both gRPC addresses. The server now treats +/// null as "keep"; these tests pin that the CLI sends null for every omitted option. +/// +public class PartialUpdateCommandTests +{ + private static readonly Option Url = new("--url") { Recursive = true }; + private static readonly Option Username = new("--username") { Recursive = true }; + private static readonly Option Password = new("--password") { Recursive = true }; + private static readonly Option Format = CliOptions.CreateFormatOption(); + + private static async Task ParseAsync( + Func, Option, Option, Option, Func, Command> build, + params string[] args) + { + var captured = new List(); + var root = new RootCommand { Url, Username, Password, Format }; + root.Add(build(Url, Format, Username, Password, cmd => { captured.Add(cmd); return 0; })); + var exit = await root.Parse(args).InvokeAsync(); + Assert.Equal(0, exit); + return Assert.IsType(Assert.Single(captured)); + } + + /// A name-only site update leaves every other field null (= unchanged). + [Fact] + public async Task SiteUpdate_NameOnly_SendsNullForEveryOtherField() + { + var cmd = await ParseAsync(SiteCommands.BuildUpdate, "update", "--id", "3", "--name", "Plant 3"); + Assert.Equal(new UpdateSiteCommand(3, "Plant 3", null, null, null, null, null), cmd); + } + + /// A site update can change one address without supplying the name. + [Fact] + public async Task SiteUpdate_AddressOnly_SendsNullName() + { + var cmd = await ParseAsync(SiteCommands.BuildUpdate, + "update", "--id", "3", "--grpc-node-a-address", "http://a:8083"); + Assert.Null(cmd.Name); + Assert.Equal("http://a:8083", cmd.GrpcNodeAAddress); + Assert.Null(cmd.GrpcNodeBAddress); + } + + /// An explicitly empty option is sent as "" (the server clears the field). + [Fact] + public async Task SiteUpdate_EmptyDescription_SendsEmptyStringToClear() + { + var cmd = await ParseAsync(SiteCommands.BuildUpdate, "update", "--id", "3", "--description", ""); + Assert.Equal("", cmd.Description); + Assert.Null(cmd.Name); + } + + /// A name-only data-connection update sends no protocol, configs or retry count. + [Fact] + public async Task DataConnectionUpdate_NameOnly_SendsNullForEveryOtherField() + { + var cmd = await ParseAsync(DataConnectionCommands.BuildUpdate, + "update", "--id", "7", "--name", "X"); + Assert.Equal(new UpdateDataConnectionCommand(7, "X", null, null, null, null), cmd); + } + + /// A passed retry count and protocol are forwarded. + [Fact] + public async Task DataConnectionUpdate_PassedOptions_AreForwarded() + { + var cmd = await ParseAsync(DataConnectionCommands.BuildUpdate, + "update", "--id", "7", "--protocol", "OpcUa", "--failover-retry-count", "5", "--backup-config", ""); + Assert.Equal(new UpdateDataConnectionCommand(7, null, "OpcUa", null, "", 5), cmd); + } + + /// A script-only api-method update keeps the timeout and both definitions. + [Fact] + public async Task ApiMethodUpdate_ScriptOnly_SendsNullTimeoutAndDefinitions() + { + var cmd = await ParseAsync(ApiMethodCommands.BuildUpdate, + "update", "--id", "5", "--script", "return 1;"); + Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", null, null, null, null), cmd); + } + + /// A timeout-only api-method update sends no script. + [Fact] + public async Task ApiMethodUpdate_TimeoutOnly_SendsNullScript() + { + var cmd = await ParseAsync(ApiMethodCommands.BuildUpdate, + "update", "--id", "5", "--timeout", "120"); + Assert.Null(cmd.Script); + Assert.Equal(120, cmd.TimeoutSeconds); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs index aade40e8..2f4dd3fb 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs @@ -4,7 +4,9 @@ using ZB.MOM.WW.ScadaBridge.CLI.Commands; namespace ZB.MOM.WW.ScadaBridge.CLI.Tests; /// -/// Regression tests for the update commands. The Update*Command records in Commons carry +/// Regression tests for the update commands. Site, data-connection and api-method updates are +/// preserve-if-null partial updates (CLI-2, see ); the +/// remaining Update*Command records in Commons carry /// non-nullable "core" fields (e.g. string Name, string Protocol, /// string Script) — an update is a whole-entity replace, not a sparse /// patch. The CLI must therefore mark those core flags as Required: making them @@ -57,15 +59,24 @@ public class UpdateCommandContractTests public void TemplateScriptUpdate_CoreFieldsRequired() => AssertRequired(UpdateCommand(TemplateCommands.Build(Url, Format, Username, Password), "script", "update"), "--name", "--code"); - /// Verifies that the site update command marks its core fields as required. + /// CLI-2: site update is a preserve-if-null partial update, so only --id is required. [Fact] - public void SiteUpdate_CoreFieldsRequired() - => AssertRequired(UpdateCommand(SiteCommands.Build(Url, Format, Username, Password), "update"), "--name"); + public void SiteUpdate_IsPartial_OnlyIdRequired() + { + var update = UpdateCommand(SiteCommands.Build(Url, Format, Username, Password), "update"); + AssertRequired(update, "--id"); + AssertOptional(update, "--name", "--description", "--node-a-address", "--node-b-address", + "--grpc-node-a-address", "--grpc-node-b-address"); + } - /// Verifies that the data connection update command marks its core fields as required. + /// CLI-2: data-connection update is a preserve-if-null partial update, so only --id is required. [Fact] - public void DataConnectionUpdate_CoreFieldsRequired() - => AssertRequired(UpdateCommand(DataConnectionCommands.Build(Url, Format, Username, Password), "update"), "--name", "--protocol"); + public void DataConnectionUpdate_IsPartial_OnlyIdRequired() + { + var update = UpdateCommand(DataConnectionCommands.Build(Url, Format, Username, Password), "update"); + AssertRequired(update, "--id"); + AssertOptional(update, "--name", "--protocol", "--primary-config", "--backup-config", "--failover-retry-count"); + } /// Verifies that the external system update command marks its core fields as required. [Fact] @@ -110,10 +121,25 @@ public class UpdateCommandContractTests } } - /// Verifies that the API method update command marks its script as required. + /// CLI-2: api-method update is a preserve-if-null partial update, so only --id is required. [Fact] - public void ApiMethodUpdate_CoreFieldsRequired() - => AssertRequired(UpdateCommand(ApiMethodCommands.Build(Url, Format, Username, Password), "update"), "--script"); + public void ApiMethodUpdate_IsPartial_OnlyIdRequired() + { + var update = UpdateCommand(ApiMethodCommands.Build(Url, Format, Username, Password), "update"); + AssertRequired(update, "--id"); + AssertOptional(update, "--script", "--timeout", "--parameters", "--return-def", "--trace-all-calls"); + } + + private static void AssertOptional(Command command, params string[] optionNames) + { + foreach (var name in optionNames) + { + var option = command.Options.SingleOrDefault(o => o.Name == name); + Assert.True(option != null, $"'{command.Name}' is missing expected option '{name}'."); + Assert.False(option!.Required, $"'{command.Name}' option '{name}' must be optional (partial update)."); + Assert.False(option.HasDefaultValue, $"'{command.Name}' option '{name}' must have no default — an omitted option must travel as null."); + } + } /// Verifies that the external system method update command keeps all of its fields optional because it is a sparse update. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Audit/FlowDebuggerDrillinTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Audit/FlowDebuggerDrillinTests.cs index b6ebd097..b56cd7a0 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Audit/FlowDebuggerDrillinTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Audit/FlowDebuggerDrillinTests.cs @@ -96,7 +96,7 @@ public class FlowDebuggerDrillinTests : BunitContext Assert.Contains("7–10 audit rows per call", markup); // Load, update and create paths all carry the flag. Assert.Contains("_traceAllCalls = _existing.TraceAllCalls;", markup); - Assert.Contains("new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)", markup); + Assert.Contains("new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim() ?? \"\", _returns?.Trim() ?? \"\", _traceAllCalls)", markup); Assert.Contains("new CreateApiMethodCommand(methodName, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)", markup); } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/PartialUpdateHandlerTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/PartialUpdateHandlerTests.cs new file mode 100644 index 00000000..9aac1a41 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/PartialUpdateHandlerTests.cs @@ -0,0 +1,215 @@ +using System.Text.Json; +using Akka.Actor; +using Akka.TestKit.Xunit2; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; + +namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests; + +/// +/// CLI-2 (WP2 task 2.8): the site, data-connection and api-method update handlers are +/// preserve-if-null. A null command field keeps the stored value; an empty string +/// clears an optional field. Before the fix every field was assigned unconditionally, +/// so site update --id 3 --name X nulled both gRPC addresses and +/// api-method update --script … reset the timeout to 30 and dropped both +/// definitions. +/// +public class PartialUpdateHandlerTests : TestKit, IDisposable +{ + private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction(); + private readonly ISiteRepository _siteRepo = Substitute.For(); + private readonly IInboundApiRepository _apiRepo = Substitute.For(); + + /// Initializes the harness with stubbed repositories. + public PartialUpdateHandlerTests() + { + _services.AddScoped(_ => _siteRepo); + _services.AddScoped(_ => _apiRepo); + _services.AddScoped(_ => Substitute.For()); + _apiRepo.SaveChangesAsync(Arg.Any()).Returns(1); + } + + /// + void IDisposable.Dispose() => Shutdown(); + + private IActorRef CreateActor() => + Sys.ActorOf(Props.Create(() => new ManagementActor( + _services.BuildServiceProvider(), NullLogger.Instance))); + + private static ManagementEnvelope Admin(object command) => + new(new AuthenticatedUser("admin", "Admin", new[] { "Administrator", "Designer" }, Array.Empty()), + command, Guid.NewGuid().ToString("N")); + + private static Site StoredSite() => new("Plant", "site-3") + { + Id = 3, + Description = "desc", + NodeAAddress = "akka.tcp://scadabridge@a:8081", + NodeBAddress = "akka.tcp://scadabridge@b:8081", + GrpcNodeAAddress = "http://a:8083", + GrpcNodeBAddress = "http://b:8083", + }; + + /// A name-only site update keeps the description and all four addresses. + [Fact] + public void UpdateSite_NameOnly_PreservesEveryOtherField() + { + var site = StoredSite(); + _siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); + + CreateActor().Tell(Admin(new UpdateSiteCommand(3, "Plant 3", null))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("Plant 3", site.Name); + Assert.Equal("desc", site.Description); + Assert.Equal("akka.tcp://scadabridge@a:8081", site.NodeAAddress); + Assert.Equal("akka.tcp://scadabridge@b:8081", site.NodeBAddress); + Assert.Equal("http://a:8083", site.GrpcNodeAAddress); + Assert.Equal("http://b:8083", site.GrpcNodeBAddress); + } + + /// An address-only site update keeps the name; an empty string clears a field. + [Fact] + public void UpdateSite_EmptyString_ClearsField_NullNameKeepsName() + { + var site = StoredSite(); + _siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); + + CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, "", GrpcNodeBAddress: ""))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("Plant", site.Name); + Assert.Null(site.Description); + Assert.Null(site.GrpcNodeBAddress); + Assert.Equal("http://a:8083", site.GrpcNodeAAddress); + } + + /// A preserved address is still validated; a malformed incoming one is refused. + [Fact] + public void UpdateSite_MalformedIncomingAddress_IsRefused() + { + var site = StoredSite(); + _siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); + + CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, null, GrpcNodeAAddress: "a:8083"))); + var error = ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Contains("GrpcNodeAAddress", error.Error); + Assert.Equal("http://a:8083", site.GrpcNodeAAddress); + } + + /// A name-only data-connection update keeps protocol, both configs and the retry count. + [Fact] + public void UpdateDataConnection_NameOnly_PreservesConfigsAndRetryCount() + { + var conn = new DataConnection("c1", "OpcUa", 1) + { + Id = 7, + PrimaryConfiguration = """{"Endpoint":"opc.tcp://p","UserIdentity":{"Password":"pw"}}""", + BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""", + FailoverRetryCount = 9, + }; + _siteRepo.GetDataConnectionByIdAsync(7, Arg.Any()).Returns(conn); + + CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, "renamed", null, null))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("renamed", conn.Name); + Assert.Equal("OpcUa", conn.Protocol); + Assert.Contains("\"pw\"", conn.PrimaryConfiguration); + Assert.Equal("""{"Endpoint":"opc.tcp://b"}""", conn.BackupConfiguration); + Assert.Equal(9, conn.FailoverRetryCount); + } + + /// An empty backup configuration removes the backup endpoint. + [Fact] + public void UpdateDataConnection_EmptyBackup_RemovesBackup() + { + var conn = new DataConnection("c1", "OpcUa", 1) + { + Id = 7, + PrimaryConfiguration = """{"Endpoint":"opc.tcp://p"}""", + BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""", + }; + _siteRepo.GetDataConnectionByIdAsync(7, Arg.Any()).Returns(conn); + + CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, null, null, null, "", 3))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Null(conn.BackupConfiguration); + Assert.Equal("""{"Endpoint":"opc.tcp://p"}""", conn.PrimaryConfiguration); + Assert.Equal(3, conn.FailoverRetryCount); + } + + /// A script-only api-method update keeps the timeout and both definitions. + [Fact] + public void UpdateApiMethod_ScriptOnly_PreservesTimeoutAndDefinitions() + { + var method = new ApiMethod("M", "return 1;") + { + Id = 5, + TimeoutSeconds = 120, + ParameterDefinitions = """[{"name":"x","type":"Integer"}]""", + ReturnDefinition = """[{"name":"y","type":"Integer"}]""", + }; + _apiRepo.GetApiMethodByIdAsync(5, Arg.Any()).Returns(method); + + CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, "return 2;", null, null, null))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("return 2;", method.Script); + Assert.Equal(120, method.TimeoutSeconds); + Assert.Equal("""[{"name":"x","type":"Integer"}]""", method.ParameterDefinitions); + Assert.Equal("""[{"name":"y","type":"Integer"}]""", method.ReturnDefinition); + } + + /// A timeout-only api-method update keeps the script; "" clears a definition. + [Fact] + public void UpdateApiMethod_TimeoutOnly_KeepsScript_EmptyClearsDefinition() + { + var method = new ApiMethod("M", "return 1;") + { + Id = 5, + TimeoutSeconds = 30, + ParameterDefinitions = """[{"name":"x","type":"Integer"}]""", + }; + _apiRepo.GetApiMethodByIdAsync(5, Arg.Any()).Returns(method); + + CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, null, 90, "", null))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("return 1;", method.Script); + Assert.Equal(90, method.TimeoutSeconds); + Assert.Null(method.ParameterDefinitions); + } + + /// + /// Wire compatibility: an older CLI always sends every field (non-null ints included); + /// that payload must still deserialize into the now-nullable records with its values. + /// + [Fact] + public void OlderClientPayloads_StillDeserialize() + { + var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; + + var dc = JsonSerializer.Deserialize( + """{"DataConnectionId":7,"Name":"X","Protocol":"OpcUa","PrimaryConfiguration":"{}","BackupConfiguration":null,"FailoverRetryCount":3}""", + options)!; + Assert.Equal(new UpdateDataConnectionCommand(7, "X", "OpcUa", "{}", null, 3), dc); + + var api = JsonSerializer.Deserialize( + """{"ApiMethodId":5,"Script":"return 1;","TimeoutSeconds":30,"ParameterDefinitions":null,"ReturnDefinition":null}""", + options)!; + Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", 30, null, null), api); + + var site = JsonSerializer.Deserialize( + """{"SiteId":3,"Name":"S","Description":null}""", options)!; + Assert.Equal(new UpdateSiteCommand(3, "S", null), site); + } +} From fe60c4a1dc871e69b8cae583cb9536e1e52ac564 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:51:00 -0500 Subject: [PATCH 4/8] fix(template-engine): resolve alarm on-trigger scripts by name per composition chain (TPL-1, TPL-2, TPL-5, WP2 tasks 2.2+2.3) Alarm -> on-trigger script links went through one flatten-wide 'TemplateScript.Id -> canonical name' map. Slot-derived templates hold only IsInherited placeholders, so every slot of a module composed twice resolved to the base script row id and the LAST slot's canonical name won: pump 1's alarm ran pump 2's script in pump 2's scope (TPL-1). A derived script override has a different row id, so the base alarm's link resolved to null (TPL-2). And the base pass over a nested slot overwrote a slot-level on-trigger override (TPL-5). ResolveInheritedAlarms now looks the id up among the script rows of the alarm's own chain, takes the row's NAME and path-qualifies it with the alarm's prefix, carrying it on the ResolvedAlarm, so only the pass that actually adds the alarm decides it. An id outside the alarm's chain keeps the old flatten-wide fallback; a name with no resolved script is still nulled. BY DESIGN this changes the revision hash of multi-slot compositions (and of derived templates that override an alarm's on-trigger script, and nested slot overrides): affected instances read Out of date once and redeploy with the corrected on-trigger script. --- docs/requirements/Component-TemplateEngine.md | 2 + .../Flattening/FlatteningService.cs | 88 ++++-- .../AlarmOnTriggerScriptResolutionTests.cs | 279 ++++++++++++++++++ 3 files changed, 347 insertions(+), 22 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Flattening/AlarmOnTriggerScriptResolutionTests.cs diff --git a/docs/requirements/Component-TemplateEngine.md b/docs/requirements/Component-TemplateEngine.md index 836b8925..a28f0c0f 100644 --- a/docs/requirements/Component-TemplateEngine.md +++ b/docs/requirements/Component-TemplateEngine.md @@ -156,6 +156,8 @@ When an instance is deployed, the Template Engine resolves the full configuratio 5. Resolve data connection bindings — replace connection name references with concrete connection details from the site. 6. Output a flat structure: list of attributes with resolved values and data source addresses, list of alarms with resolved trigger definitions, list of scripts with resolved code and triggers. +**Alarm on-trigger script resolution (2026-12-03, TPL-1/TPL-2/TPL-5).** An alarm's `OnTriggerScriptId` is resolved **by name within the alarm's own chain**: the id is looked up among the script rows of every template in that alarm's inheritance chain (base rows, derived overrides and `IsInherited` placeholders), and the row's *name* is path-qualified with the alarm's composition prefix (`Pump1.HighTemp` → `Pump1.OnHigh`). It used to go through one flatten-wide `script id → canonical name` map, which (a) made every slot of a module composed twice run the **last** slot's script, since all slots share the base script row id; (b) dropped the link (null on-trigger script) when a derived template overrode the script, since the override row has a different id; and (c) let the second visit of a nested slot overwrite a slot-level on-trigger override. The value is decided by the pass that actually adds the alarm (first wins, same as the alarm itself). An id that is not a script row of the alarm's own chain keeps the old flatten-wide fallback, and a reference that names no resolved script is still left null. **This changes the revision hash** of any instance whose flattened alarms were affected — such instances read *Out of date* once and redeploy with the corrected script link. + ### Flatten-session caching and the graph watermark (WP2.5) The flatten above is driven per instance, so an unmemoised implementation re-walks diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Flattening/FlatteningService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Flattening/FlatteningService.cs index 1fca35fb..06b7eea5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Flattening/FlatteningService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Flattening/FlatteningService.cs @@ -78,11 +78,15 @@ public class FlatteningService // Step 4: Apply connection bindings ApplyConnectionBindings(instance.ConnectionBindings, attributes, dataConnections); - // Step 5: Resolve alarms from inheritance chain. - // alarmScriptIds maps a resolved alarm's canonical name to the - // TemplateScript.Id of its on-trigger script (if any). + // Step 5: Resolve alarms from inheritance chain. Each alarm's on-trigger + // script is resolved by NAME within the alarm's own chain and + // path-qualified with the alarm's prefix (TPL-1/TPL-2/TPL-5). + // alarmScriptIds only carries the legacy fallback: an on-trigger script + // id that is not a script row of the alarm's own chain. var alarmScriptIds = new Dictionary(StringComparer.Ordinal); - var alarms = ResolveInheritedAlarms(templateChain, prefix: null, alarmScriptIds); + var alarms = ResolveInheritedAlarms(templateChain, prefix: null, out var rootUnresolvedScriptIds); + foreach (var (alarmName, scriptId) in rootUnresolvedScriptIds) + alarmScriptIds[alarmName] = scriptId; ResolveComposedAlarms(templateChain, compositionMap, composedTemplateChains, alarms, alarmScriptIds); ApplyInstanceAlarmOverrides(instance.AlarmOverrides, alarms); @@ -94,7 +98,7 @@ public class FlatteningService ResolveComposedScripts(templateChain, compositionMap, composedTemplateChains, scripts, scriptCanonicalById); // Step 7: Resolve alarm on-trigger script references to canonical names - ResolveAlarmScriptReferences(alarms, alarmScriptIds, scriptCanonicalById); + ResolveAlarmScriptReferences(alarms, alarmScriptIds, scriptCanonicalById, scripts); // Step 7b: Resolve native alarm source bindings (connection + source // reference). Conditions under each source are discovered at runtime; @@ -405,19 +409,39 @@ public class FlatteningService /// Resolves alarms from an inheritance chain. When /// is non-null the alarm names are returned bare (caller path-qualifies); /// the keys of the returned dictionary are always bare alarm names. - /// is populated with the on-trigger - /// script id of each resolved alarm keyed by the canonical name the alarm - /// will ultimately carry (bare name when is null, - /// otherwise prefix.name). + /// + /// Each alarm's on-trigger script is resolved within this chain: the + /// OnTriggerScriptId is looked up among the script rows of every + /// template in and translated to that row's + /// NAME, which is then path-qualified with and set + /// as . Resolving by + /// name per chain (not through a flatten-wide id map) is what keeps two + /// slots of the same module apart (TPL-1: both slots share the base script + /// row id, so a global map made every slot's alarm run the LAST slot's + /// script) and keeps the link when a derived template overrides the script + /// with a row of a different id (TPL-2). The value travels on the alarm, so + /// only the pass that actually adds the alarm decides it (TPL-5). + /// + /// receives, keyed by bare alarm name, + /// any on-trigger script id that is NOT a script row of this chain; the + /// caller records it for the legacy flatten-wide id fallback. /// private static Dictionary ResolveInheritedAlarms( IReadOnlyList