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.
This commit is contained in:
Joseph Doherty
2026-12-03 09:48:00 -05:00
parent c207809ef3
commit 61c6278bd0
17 changed files with 533 additions and 93 deletions
@@ -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;
/// <summary>
/// CLI-2 (WP2 task 2.8): <c>site update</c>, <c>data-connection update</c> and
/// <c>api-method update</c> send only the options actually passed. Before the fix an
/// omitted option was sent as null (or as a default: <c>--failover-retry-count</c> 3,
/// <c>--timeout</c> 30) and the server overwrote the stored value — e.g.
/// <c>site update --id 3 --name X</c> nulled both gRPC addresses. The server now treats
/// null as "keep"; these tests pin that the CLI sends null for every omitted option.
/// </summary>
public class PartialUpdateCommandTests
{
private static readonly Option<string> Url = new("--url") { Recursive = true };
private static readonly Option<string> Username = new("--username") { Recursive = true };
private static readonly Option<string> Password = new("--password") { Recursive = true };
private static readonly Option<string> Format = CliOptions.CreateFormatOption();
private static async Task<T> ParseAsync<T>(
Func<Option<string>, Option<string>, Option<string>, Option<string>, Func<object, int>, Command> build,
params string[] args)
{
var captured = new List<object>();
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<T>(Assert.Single(captured));
}
/// <summary>A name-only site update leaves every other field null (= unchanged).</summary>
[Fact]
public async Task SiteUpdate_NameOnly_SendsNullForEveryOtherField()
{
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate, "update", "--id", "3", "--name", "Plant 3");
Assert.Equal(new UpdateSiteCommand(3, "Plant 3", null, null, null, null, null), cmd);
}
/// <summary>A site update can change one address without supplying the name.</summary>
[Fact]
public async Task SiteUpdate_AddressOnly_SendsNullName()
{
var cmd = await ParseAsync<UpdateSiteCommand>(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);
}
/// <summary>An explicitly empty option is sent as "" (the server clears the field).</summary>
[Fact]
public async Task SiteUpdate_EmptyDescription_SendsEmptyStringToClear()
{
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate, "update", "--id", "3", "--description", "");
Assert.Equal("", cmd.Description);
Assert.Null(cmd.Name);
}
/// <summary>A name-only data-connection update sends no protocol, configs or retry count.</summary>
[Fact]
public async Task DataConnectionUpdate_NameOnly_SendsNullForEveryOtherField()
{
var cmd = await ParseAsync<UpdateDataConnectionCommand>(DataConnectionCommands.BuildUpdate,
"update", "--id", "7", "--name", "X");
Assert.Equal(new UpdateDataConnectionCommand(7, "X", null, null, null, null), cmd);
}
/// <summary>A passed retry count and protocol are forwarded.</summary>
[Fact]
public async Task DataConnectionUpdate_PassedOptions_AreForwarded()
{
var cmd = await ParseAsync<UpdateDataConnectionCommand>(DataConnectionCommands.BuildUpdate,
"update", "--id", "7", "--protocol", "OpcUa", "--failover-retry-count", "5", "--backup-config", "");
Assert.Equal(new UpdateDataConnectionCommand(7, null, "OpcUa", null, "", 5), cmd);
}
/// <summary>A script-only api-method update keeps the timeout and both definitions.</summary>
[Fact]
public async Task ApiMethodUpdate_ScriptOnly_SendsNullTimeoutAndDefinitions()
{
var cmd = await ParseAsync<UpdateApiMethodCommand>(ApiMethodCommands.BuildUpdate,
"update", "--id", "5", "--script", "return 1;");
Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", null, null, null, null), cmd);
}
/// <summary>A timeout-only api-method update sends no script.</summary>
[Fact]
public async Task ApiMethodUpdate_TimeoutOnly_SendsNullScript()
{
var cmd = await ParseAsync<UpdateApiMethodCommand>(ApiMethodCommands.BuildUpdate,
"update", "--id", "5", "--timeout", "120");
Assert.Null(cmd.Script);
Assert.Equal(120, cmd.TimeoutSeconds);
}
}
@@ -4,7 +4,9 @@ using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// Regression tests for the update commands. The <c>Update*Command</c> 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 <see cref="PartialUpdateCommandTests"/>); the
/// remaining <c>Update*Command</c> records in Commons carry
/// non-nullable "core" fields (e.g. <c>string Name</c>, <c>string Protocol</c>,
/// <c>string Script</c>) — an update is a <em>whole-entity replace</em>, not a sparse
/// patch. The CLI must therefore mark those core flags as <c>Required</c>: 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");
/// <summary>Verifies that the site update command marks its core fields as required.</summary>
/// <summary>CLI-2: site update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[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");
}
/// <summary>Verifies that the data connection update command marks its core fields as required.</summary>
/// <summary>CLI-2: data-connection update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[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");
}
/// <summary>Verifies that the external system update command marks its core fields as required.</summary>
[Fact]
@@ -110,10 +121,25 @@ public class UpdateCommandContractTests
}
}
/// <summary>Verifies that the API method update command marks its script as required.</summary>
/// <summary>CLI-2: api-method update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[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.");
}
}
/// <summary>Verifies that the external system method update command keeps all of its fields optional because it is a sparse update.</summary>
[Fact]
@@ -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);
}
}
@@ -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;
/// <summary>
/// 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 <c>site update --id 3 --name X</c> nulled both gRPC addresses and
/// <c>api-method update --script …</c> reset the timeout to 30 and dropped both
/// definitions.
/// </summary>
public class PartialUpdateHandlerTests : TestKit, IDisposable
{
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
private readonly IInboundApiRepository _apiRepo = Substitute.For<IInboundApiRepository>();
/// <summary>Initializes the harness with stubbed repositories.</summary>
public PartialUpdateHandlerTests()
{
_services.AddScoped(_ => _siteRepo);
_services.AddScoped(_ => _apiRepo);
_services.AddScoped(_ => Substitute.For<IAuditService>());
_apiRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
}
/// <inheritdoc />
void IDisposable.Dispose() => Shutdown();
private IActorRef CreateActor() =>
Sys.ActorOf(Props.Create(() => new ManagementActor(
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
private static ManagementEnvelope Admin(object command) =>
new(new AuthenticatedUser("admin", "Admin", new[] { "Administrator", "Designer" }, Array.Empty<string>()),
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",
};
/// <summary>A name-only site update keeps the description and all four addresses.</summary>
[Fact]
public void UpdateSite_NameOnly_PreservesEveryOtherField()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, "Plant 3", null)));
ExpectMsg<ManagementSuccess>(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);
}
/// <summary>An address-only site update keeps the name; an empty string clears a field.</summary>
[Fact]
public void UpdateSite_EmptyString_ClearsField_NullNameKeepsName()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, "", GrpcNodeBAddress: "")));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("Plant", site.Name);
Assert.Null(site.Description);
Assert.Null(site.GrpcNodeBAddress);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
}
/// <summary>A preserved address is still validated; a malformed incoming one is refused.</summary>
[Fact]
public void UpdateSite_MalformedIncomingAddress_IsRefused()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, null, GrpcNodeAAddress: "a:8083")));
var error = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(10));
Assert.Contains("GrpcNodeAAddress", error.Error);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
}
/// <summary>A name-only data-connection update keeps protocol, both configs and the retry count.</summary>
[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<CancellationToken>()).Returns(conn);
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, "renamed", null, null)));
ExpectMsg<ManagementSuccess>(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);
}
/// <summary>An empty backup configuration removes the backup endpoint.</summary>
[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<CancellationToken>()).Returns(conn);
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, null, null, null, "", 3)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Null(conn.BackupConfiguration);
Assert.Equal("""{"Endpoint":"opc.tcp://p"}""", conn.PrimaryConfiguration);
Assert.Equal(3, conn.FailoverRetryCount);
}
/// <summary>A script-only api-method update keeps the timeout and both definitions.</summary>
[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<CancellationToken>()).Returns(method);
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, "return 2;", null, null, null)));
ExpectMsg<ManagementSuccess>(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);
}
/// <summary>A timeout-only api-method update keeps the script; "" clears a definition.</summary>
[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<CancellationToken>()).Returns(method);
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, null, 90, "", null)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("return 1;", method.Script);
Assert.Equal(90, method.TimeoutSeconds);
Assert.Null(method.ParameterDefinitions);
}
/// <summary>
/// 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.
/// </summary>
[Fact]
public void OlderClientPayloads_StillDeserialize()
{
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var dc = JsonSerializer.Deserialize<UpdateDataConnectionCommand>(
"""{"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<UpdateApiMethodCommand>(
"""{"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<UpdateSiteCommand>(
"""{"SiteId":3,"Name":"S","Description":null}""", options)!;
Assert.Equal(new UpdateSiteCommand(3, "S", null), site);
}
}